Search code examples
pythonlogarithm

how to compute logarithms in Python not using math.log


in a while loop of a code of mine the while breaks because

>>> 3<=abs(math.log(1000,10))
False

but, of course the log of 1000 in base 10 is exactly 3, so i was confident that the condition should work...

But in fact i have this:

>>> abs(math.log(1000,10))
2.9999999999999996 

So i would like any suggestions: is there a "best practice" rounding the result or is there a smarter method to compute logarithms? Thanks a lot!


Solution

  • For base 10 you should use:

    math.log10(x)
    

    It returns the base-10 logarithm of x. This is usually more accurate than log(x, 10).