Python math module logarithm functions
Possible duplicate:
Inaccurate logarithm in Python
Why are the results math.log10(x)
and math.log(x,10)
different?
In [1]: from math import *
In [2]: log10(1000)
Out[2]: 3.0
In [3]: log(1000,10)
Out[3]: 2.9999999999999996
source to share
math.log10
and math.log(x, 10)
use a different algorithm, and the first is usually more accurate. This is actually a known issue (Issue6765): math.log, log10 mismatch .
You can think this way: it log10(x)
has a fixed base, so it can be calculated directly using some mathematical approximation formula (for example, the Taylor series), but log(x, 10)
from a more general formula with two variables, which can be indirectly calculated on log(x) / log(10)
(at least the accuracy of log ( 10) will affect the accuracy of the quotient). Naturally, the former method is faster and more accurate, and this is reasonable, given that it uses a previously known logarithmic base (i.e. 10).
source to share
This is a known bug: http://bugs.python.org/issue3724
It seems that logX (y) is always more accurate than the equivalent log (Y, X).
source to share
As others have pointed out, log(1000, 10)
computed internally as log(1000) / log(10)
. This can be verified empirically:
In [3]: math.log(1000, 10) == math.log(1000) / math.log(10)
Out[3]: True
In [4]: math.log10(1000) == math.log(1000) / math.log(10)
Out[4]: False
The results are neither log(1000)
, nor log(10)
can they be presented as float
, so the end result is also imprecise.
source to share