ValueError: math domain error
What it means
You asked a math function for an answer that does not exist among real numbers. The usual cases are math.sqrt() of a negative number, math.log() of zero or a negative number, and math.acos() or math.asin() of a value outside -1 to 1.
1. Square root of a negative number
This raises the error
Traceback (most recent call last): File "<exec>", line 4, in <module> ValueError: math domain error
The fix
No real roots. Complex root: (-1+2j)
A negative number has no real square root. Check the value first, or use cmath.sqrt(), which returns a complex number.
2. Logarithm of zero or a negative number
This raises the error
2.0791812460476247 1.6532125137753437 Traceback (most recent call last): File "<exec>", line 4, in <module> ValueError: math domain error
The fix
2.079 1.653 0 has no logarithm, skipped 2.477
Logarithms exist only for numbers above zero, so skip or replace zeros and negatives first. In data work, math.log(x + 1) is a common way to keep zeros.
3. A value just outside -1 to 1 because of rounding
This raises the error
1.0000000000000002 Traceback (most recent call last): File "<exec>", line 4, in <module> ValueError: math domain error
The fix
0.0
Float arithmetic can land a hair outside the allowed range, here 1.0000000000000002. Clamping the value into -1 to 1 before acos() or asin() removes the rounding error.
When you see this error, check
- Print the value you pass to the
mathfunction. sqrt()needs 0 or more,log()needs more than 0, andacos()andasin()need -1 to 1.- Clamp values that come from float calculations before passing them on.
- Use the
cmathmodule if you really want complex results.
Related errors
All Python errors · How to read a traceback · Step through your code