Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python math domain errors in math.log function

Tags:

python

math

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?

like image 613
Felix Avatar asked Sep 30 '13 13:09

Felix


People also ask

How do I fix the math domain error in Python?

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.

How do you get rid of domain error in math?

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.

What is math domain error?

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.


1 Answers

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 
like image 83
Sven Marnach Avatar answered Sep 18 '22 21:09

Sven Marnach