zlacker

[return to "My Favorite Programming Problem to Teach: Digit Length"]
1. jepler+N3[view] [source] 2019-11-10 22:44:41
>>jstrie+(OP)
But the math.log10 solution is unfortunately "wrong" too, at least in my python3 implementation.

    import math

    def digitLengthCorrect(n):
        return len(str(n))

    def digitLengthClever2(n):
        return 1 if n == 0 else (math.floor(math.log10(n)) + 1)

    testcases = (
        [10 ** i for i in range(300)] +
        [(10 ** i) - 1 for i in range(300)]
    )

    for t in testcases:
        a = digitLengthCorrect(t)
        b = digitLengthClever2(t)
        assert a == b, (t, a, b)
◧◩
2. jdnier+ew[view] [source] 2019-11-11 05:37:29
>>jepler+N3
Sure enough. This may help show what happens with float precision:

    >>> import math
    >>>
    >>> for i in range(1, 20):
    ...     n = int('9' * i)
    ...     digitLengthClever2 = math.floor(math.log10(n) + 1)
    ...     float_value = math.log10(n)
    ...     print(f'{n:<20} {digitLengthClever2:>2}  {float_value}')
    ...
    9                     1  0.9542425094393249
    99                    2  1.99563519459755
    999                   3  2.9995654882259823
    9999                  4  3.9999565683801923
    99999                 5  4.999995657033466
    999999                6  5.999999565705301
    9999999               7  6.99999995657055
    99999999              8  7.999999995657055
    999999999             9  8.999999999565706
    9999999999           10  9.99999999995657
    99999999999          11  10.999999999995657
    999999999999         12  11.999999999999567
    9999999999999        13  12.999999999999957
    99999999999999       14  13.999999999999996  # <-
    999999999999999      16  15.0                # <- 
    9999999999999999     17  16.0
    99999999999999999    18  17.0
    999999999999999999   19  18.0
    9999999999999999999  20  19.0
[go to top]