Python ValueError: math domain error (Causes and Fixes)

Your script was log-scaling customer balances, then it hit a $0.00 account and stopped with ValueError: math domain error. Python’s telling you a math function got a number outside the range it accepts.

Quick answer: math.sqrt() needs x >= 0, math.log() needs x > 0, and math.acos() or asin() need a value from -1 to 1. Check the value first, catch ValueError, or use cmath:

score = math.log10(usd) if usd > 0 else None

In this tutorial, we’ll fix ValueError: math domain error on one small dataset. Outputs are real, from Python 3.12.5 and Python 3.14.8.

What You Need Before You Start Fixing the Math Domain Error

Just Python 3.8 or newer; math.cbrt() in Step 5 needs 3.11+. Our running sample is four customer balances, one zero and one negative:

import math

balances = {"Emily Carter": 1250.00, "James Miller": 0.00,
            "Olivia Brooks": 8400.50, "Ryan Hayes": -75.25}

New to the module? Our guide to the Python math module lists what each function does.

Step 1: Reproduce ValueError: math domain error with math.log10()

I always run the failing code first. This loop log-scales each balance for a chart:

import math

balances = {"Emily Carter": 1250.00, "James Miller": 0.00,
            "Olivia Brooks": 8400.50, "Ryan Hayes": -75.25}

for name, usd in balances.items():
    score = math.log10(usd)
    print(f"{name:<14} ${usd:>9,.2f}  log10 = {score:.3f}")

Output:

Emily Carter   $ 1,250.00  log10 = 3.097
Traceback (most recent call last):
  File "C:\pyguides\pydemo\math_domain_log.py", line 7, in <module>
    score = math.log10(usd)
            ^^^^^^^^^^^^^^^
ValueError: math domain error
VS Code traceback of Python ValueError: math domain error raised by math.log10 on a zero balance
The zero balance makes math.log10() raise the error.

The traceback points at math.log10(usd). Like other types of errors in Python, an unhandled ValueError ends the script.

Step 2: Find which math function got an out-of-domain value

The message doesn’t name the bad value, so test the usual suspects on Python 3.12:

import math

calls = {
    "sqrt(-16)":     lambda: math.sqrt(-16),
    "log(0)":        lambda: math.log(0),
    "acos(1.2)":     lambda: math.acos(1.2),
    "asin(-1.5)":    lambda: math.asin(-1.5),
    "pow(-8, 1/3)":  lambda: math.pow(-8, 1 / 3),
}
for label, call in calls.items():
    try:
        print(f"{label:<14} {call()}")
    except ValueError as err:
        print(f"{label:<14} ValueError: {err}")

Output:

sqrt(-16)      ValueError: math domain error
log(0)         ValueError: math domain error
acos(1.2)      ValueError: math domain error
asin(-1.5)     ValueError: math domain error
pow(-8, 1/3)   ValueError: math domain error

Negative square roots and logs of zero are the usual culprits. Our square root in Python tutorial covers math.sqrt() itself.

Step 3: Validate the input or catch the ValueError

Same four balances, now checked before log10():

# import math + balances: same as the sample above
for name, usd in balances.items():
    if usd > 0:
        print(f"{name:<14} ${usd:>9,.2f}  log10 = {math.log10(usd):.3f}")
    else:
        print(f"{name:<14} ${usd:>9,.2f}  skipped: log10 needs > 0")

Output:

Emily Carter   $ 1,250.00  log10 = 3.097
James Miller   $     0.00  skipped: log10 needs > 0
Olivia Brooks  $ 8,400.50  log10 = 3.924
Ryan Hayes     $   -75.25  skipped: log10 needs > 0
Before and after: Python math domain error traceback on a zero balance, then the fixed loop skipping zero and negative balances
Without the check the loop dies; with it, all four rows print.

If you’d rather keep the happy path short, wrap only the math call and catch ValueError, never a bare except:

# import math + balances: same as the sample above
def log_score(usd):
    try:
        return round(math.log10(usd), 3)
    except ValueError:
        return None

print({name: log_score(usd) for name, usd in balances.items()})

Output:

{'Emily Carter': 3.097, 'James Miller': None, 'Olivia Brooks': 3.924, 'Ryan Hayes': None}

Balances read as text can fail earlier with could not convert string to float.

Step 4: Clamp floating-point rounding before acos() or asin()

A spending vector compared with itself should give a cosine of exactly 1, but floats round:

import math

march = [1.1, 2.2, 3.3]              # spend in $1,000s
dot = sum(a * b for a, b in zip(march, march))
cos = dot / (math.sqrt(dot) * math.sqrt(dot))
print("cosine:", repr(cos))

try:
    math.acos(cos)
except ValueError as err:
    print("acos failed:", err)

safe = max(-1.0, min(1.0, cos))
print("angle:", math.degrees(math.acos(safe)), "degrees")

Output:

cosine: 1.0000000000000002
acos failed: math domain error
angle: 0.0 degrees
VS Code output showing a cosine of 1.0000000000000002 causing a math domain error in math.acos, fixed by clamping
A cosine just above 1 fails until it’s clamped.

Clamping is safe because the overshoot is rounding noise. For the angle units, see degrees and radians in Python.

Step 5: Use cmath or math.cbrt() for negative numbers

Sometimes a negative input is valid and you want an answer:

import cmath
import math

print(cmath.sqrt(-16))
print(math.cbrt(-8))                 # Python 3.11+
print((-8) ** (1 / 3))

Output:

4j
-2.0
(1.0000000000000002+1.7320508075688772j)

math.pow(-8, 1/3) fails, while ** quietly returns a complex number. Our exponents in Python guide compares the operators.

Which inputs does each math function accept?

FunctionValid inputFix
math.sqrt(x)x >= 0Check, or cmath.sqrt()
math.log(x), log10, log2x > 0Check first
math.acos(x), asin(x)-1 to 1Clamp rounding noise
math.pow(x, y)No negative x with fractional ymath.cbrt()

Why does Python 3.14 show a different math domain error message?

Python 3.14 gives most functions a specific message. Here’s the Step 2 script on 3.14:

Output on Python 3.14:

sqrt(-16)      ValueError: expected a nonnegative input, got -16.0
log(0)         ValueError: expected a positive input
acos(1.2)      ValueError: expected a number in range from -1 up to 1, got 1.2
asin(-1.5)     ValueError: expected a number in range from -1 up to 1, got -1.5
pow(-8, 1/3)   ValueError: math domain error
VS Code output of Python 3.14 showing new math domain error messages such as expected a positive input
Python 3.14 names the problem, except for math.pow().

It’s still a ValueError, so except ValueError works on both. Don’t match the message text.

Common Mistakes to Avoid with Math Domain Errors

  • Checking x >= 0 before log(). Zero fails too.
  • Wrapping a whole block in try. Unrelated bugs get hidden.
  • Using abs() to silence it. A $75.25 debt isn’t a $75.25 balance.

Next Steps after Fixing the Math Domain Error

A negative discriminant is where this error shows up next. Our quadratic equation in Python tutorial handles it with cmath.

Once this runs clean, these guides pair well with it:

Frequently asked questions

What does ValueError: math domain error mean?

A math function got an input outside its domain.

How do I fix math domain error in math.log()?

Check that the value is greater than 0, or catch ValueError.

Why does math.acos() fail on 1?

Rounding gave 1.0000000000000002. Clamp with max(-1.0, min(1.0, x)).

Does NumPy raise a math domain error?