What is the purpose of numpy.log1p( )? What is the purpose of numpy.log1p( )? numpy numpy

What is the purpose of numpy.log1p( )?


The NumPy docs give a hint:

For real-valued input, log1p is accurate also for x so small that 1 + x == 1 in floating-point accuracy.

So for example let's add a tiny non-zero number and 1.0. Rounding errors make it a 1.0.

>>> 1e-100 == 0.0False>>> 1e-100 + 1.0 == 1.0True

If we try to take the log of that incorrect sum, we get an incorrect result (compare to WolframAlpha):

>>> np.log(1e-100 + 1)0.0

But if we use log1p(), we get the correct result

>>> np.log1p(1e-100)1e-100

The same principle holds for exp1m() and logaddexp(): The're more accurate for small x.


https://docs.scipy.org/doc/numpy/reference/generated/numpy.log1p.html

enter image description here

If x is in range 0...+Inf then it will never cause an error (as we know log(0) would cause an error).

Not always the best choice, because as you see you will lose a big curve before x = 0 that is one of the best things about log function


When your input value is so small, using np.log1p or np.expm1 to calculate, you will get the more accutrate result than np.log or np.exp according to the interpretation from this link.