Editor

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

Broken
import math
a, b, c = 1, 2, 5
d = b ** 2 - 4 * a * c
root = (-b + math.sqrt(d)) / (2 * a)
print(root)
Output
Traceback (most recent call last):
  File "<exec>", line 4, in <module>
ValueError: math domain error

The fix

Fixed
import math
import cmath
a, b, c = 1, 2, 5
d = b ** 2 - 4 * a * c
if d >= 0:
print((-b + math.sqrt(d)) / (2 * a))
else:
print('No real roots. Complex root:', (-b + cmath.sqrt(d)) / (2 * a))
Output
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.

Try fixing it yourself in the editor

2. Logarithm of zero or a negative number

This raises the error

Broken
import math
sales = [120, 45, 0, 300]
for s in sales:
print(math.log10(s))
Output
2.0791812460476247
1.6532125137753437
Traceback (most recent call last):
  File "<exec>", line 4, in <module>
ValueError: math domain error

The fix

Fixed
import math
sales = [120, 45, 0, 300]
for s in sales:
if s > 0:
print(round(math.log10(s), 3))
else:
print(s, 'has no logarithm, skipped')
Output
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.

Try fixing it yourself in the editor

3. A value just outside -1 to 1 because of rounding

This raises the error

Broken
import math
ratio = (0.1 + 0.2) / 0.3
print(ratio)
angle = math.acos(ratio)
print(angle)
Output
1.0000000000000002
Traceback (most recent call last):
  File "<exec>", line 4, in <module>
ValueError: math domain error

The fix

Fixed
import math
ratio = (0.1 + 0.2) / 0.3
ratio = max(-1.0, min(1.0, ratio)) # clamp into -1 to 1
angle = math.acos(ratio)
print(angle)
Output
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.

Try fixing it yourself in the editor

When you see this error, check

  • Print the value you pass to the math function.
  • sqrt() needs 0 or more, log() needs more than 0, and acos() and asin() need -1 to 1.
  • Clamp values that come from float calculations before passing them on.
  • Use the cmath module if you really want complex results.

All Python errors · How to read a traceback · Step through your code