I have to use Python math.log(x)
function with values of x from (0, ..., 1). Sometimes x may be too close to zero, and Python gives me an error:
ValueError: math domain error
How can I know, what is the domain of definition of math.log
function?
To solve the math domain error in Python, we need to prevent the user so that he cannot calculate the square root of a negative number before we execute the math. sqrt() function.
The ValueError: math domain error is raised when you perform a mathematical function on a negative or zero number which cannot be computed. To solve this error, make sure you are using a valid number for the mathematical function you are using.
A domain error occurs if an input argument is outside the domain over which the mathematical function is defined. Paragraph 3 states. A pole error (also known as a singularity or infinitary) occurs if the mathematical function has an exact infinite result as the finite input argument(s) are approached in the limit.
As long as your input is within the half-open interval (0, 1] (not including 0), you are fine. You can't be too close to zero:
>>> math.log(sys.float_info.min) -708.3964185322641
So simply checking for exactly zero (maybe as the result of an underflow) should be enough, or alternatively catch the exception and handle it.
EDIT: This also holds for the denormal minimum floating point number:
>>> math.log(sys.float_info.min * sys.float_info.epsilon) -744.4400719213812
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With