0

I'm seeing strange behavior with base 10 logarithms in python 2.7.

int(log(10**6,10))

incorrectly returns 5, while

int(log10(10**6))

correctly returns 6. What's going on here?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
spitespike
  • 179
  • 3
  • `log` is not a Python builtin, so it's not clear what your code is doing. You mean `import math; math.log`? – Edward D'Souza Oct 19 '16 at 02:10
  • `math.log(10**6, 10)` yields `5.999999999999999`, and `float`->`int` conversion truncates the decimal portion. – John Kugelman Oct 19 '16 at 02:12
  • The question marked as duplicate is not a duplicate. This is ridiculous. @JohnKugelman – Edward D'Souza Oct 19 '16 at 02:14
  • @EdwardD'Souza - It's certainly a duplicate, and not ridiculous at all. `math.log` uses floating-point arithmetic, which can be inaccurate, leading to this sort of error. – TigerhawkT3 Oct 19 '16 at 02:16
  • The problem, as pointed out by @JohnKugelman is floating point error. The Python docs (https://docs.python.org/2/library/math.html) incorrectly state that `math.log` returns "the natural logarithm of x". In fact, it doesn't in many cases. It actually returns a floating point approximation of it, which your use of an `int` cast masks. – Edward D'Souza Oct 19 '16 at 02:19
  • @TigerhawkT3 If this question was a duplicate, there would be no need for the explanation given in [this comment](http://stackoverflow.com/questions/40120918/unexpected-base-10-logarithm-behavior?noredirect=1#comment67512854_40120918). Instead of marking this as a duplicate, and the proceeding to actually answer the question in the comments (which is against the design of SO), the proper thing would be to post that comment as an answer. – Edward D'Souza Oct 19 '16 at 02:31

0 Answers0