math.log uses floats and these almost always involve some rounding errors.
>>> math.log(1000, 10)
2.9999999999999996
If you need it to be exact you should change your algorithm to generate the powers of 10 (simply multiply the last power by 10) and continue as long as the new power is smaller than your input number.
>>> limit = 12345
>>> power = 10
>>> while power < limit:
... print power
... power = power * 10
...
10
100
1000
10000
This is guaranteed to be exact as it does not involve any floating point numbers. (And is a lot faster, too)
Answer from bikeshedder on Stack OverflowVideos
math.log uses floats and these almost always involve some rounding errors.
>>> math.log(1000, 10)
2.9999999999999996
If you need it to be exact you should change your algorithm to generate the powers of 10 (simply multiply the last power by 10) and continue as long as the new power is smaller than your input number.
>>> limit = 12345
>>> power = 10
>>> while power < limit:
... print power
... power = power * 10
...
10
100
1000
10000
This is guaranteed to be exact as it does not involve any floating point numbers. (And is a lot faster, too)
Floating-point math strikes again! Look at the values returned by math.log:
>>> math.log(10000, 10)
4.0
>>> math.log(1000, 10)
2.9999999999999996
>>> math.log(100, 10)
2.0
>>> math.log(10, 10)
1.0
I add math.log() method in a function but it took more step to compute than iterative version of the same function unless input is power of 2 because log is base 2. What I want to learn is does math.log() method have more than constant time complexity ?