Home > Net >  What is the smallest value you can pass to np.log()?
What is the smallest value you can pass to np.log()?

Time:01-17

How do I find the smallest (real, positive) float32 value I can pass to numpy.log() and get a non-NaN result?

I would have thought that the tiny value returned by finfo(np.float32) would work, but it does not:

>>> float_info = np.finifo(np.float32)
>>> float_info.tiny
1.1754944e-38
>>> np.log(float_info.tiny)
nan

UPDATE:

Voting to close this -- I made a typo. np.log(float_info.tiny) returns -87.33655, not NaN.

CodePudding user response:

In the numpy library, the np.log() function calculates the natural logarithm (base e) of the input. The input must be a positive number, because the natural logarithm of a negative number or zero is not defined.

The smallest positive value that can be passed to np.log() is the smallest representable positive number in Python, which is approximately 2.22e-308. If you pass a value smaller than this to the function, you will get an error, because that value is not representable as a floating-point number.

For example, the following code will raise an error because the value passed to np.log() is too small:

import numpy as np

x = np.finfo(np.float32).eps
print(np.log(x))

This will raise a "math domain error" because the value passed to np.log() is too small.

It's worth noting that the smallest positive value is not the only limit for logarithm function, the maximum value that can be passed to the logarithm function depends on the type of the input, for instance, if you use the numpy.log() function with a very large value, you might get an "overflow" error.

CodePudding user response:

Note that smallest_normal is not actually the smallest positive representable value in a NumPy floating point type.

Source: https://numpy.org/doc/stable/reference/generated/numpy.finfo.html

I would assume this is the reason why it's not working.

  • Related