Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inaccurate Logarithm in Python

I work daily with Python 2.4 at my company. I used the versatile logarithm function 'log' from the standard math library, and when I entered log(2**31, 2) it returned 31.000000000000004, which struck me as a bit odd.

I did the same thing with other powers of 2, and it worked perfectly. I ran 'log10(2**31) / log10(2)' and I got a round 31.0

I tried running the same original function in Python 3.0.1, assuming that it was fixed in a more advanced version.

Why does this happen? Is it possible that there are some inaccuracies in mathematical functions in Python?

like image 822
Avihu Turzion Avatar asked May 31 '09 12:05

Avihu Turzion


People also ask

What does .log mean in Python?

Definition and Usage log() method returns the natural logarithm of a number, or the logarithm of number to base.

How do you solve logs in Python?

Understanding the log() functions in Python We need to use the math module to access the log functions in the code. The math. log(x) function is used to calculate the natural logarithmic value i.e. log to the base e (Euler's number) which is about 2.71828, of the parameter value (numeric expression), passed to it.

Does Python log natural log?

Note that Python's log function calculates the natural log of a number.


1 Answers

This is to be expected with computer arithmetic. It is following particular rules, such as IEEE 754, that probably don't match the math you learned in school.

If this actually matters, use Python's decimal type.

Example:

from decimal import Decimal, Context
ctx = Context(prec=20)
two = Decimal(2)
ctx.divide(ctx.power(two, Decimal(31)).ln(ctx), two.ln(ctx))
like image 68
Matthew Flaschen Avatar answered Oct 15 '22 11:10

Matthew Flaschen