ValueError: Math Domain Error

ValueError: math domain error

Quick Answer

You passed an invalid value to a math function, such as sqrt of a negative number or log of zero. Validate inputs before calling math functions.

Why This Happens

Math functions have domain restrictions: math.sqrt() needs non-negative, math.log() needs positive, math.asin()/acos() need [-1, 1]. Use cmath for complex results.

The Problem

import math
result = math.sqrt(-1)
log_val = math.log(0)

The Fix

import math
if value >= 0:
    result = math.sqrt(value)
else:
    import cmath
    result = cmath.sqrt(value)

Step-by-Step Fix

  1. 1

    Validate inputs

    Check values are within valid domain.

  2. 2

    Use cmath for complex

    Import cmath for operations returning complex numbers.

  3. 3

    Clamp values

    Use max()/min() to keep values in valid bounds.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free