How to Fix: ValueError: math domain error

3D illustration of a square root machine rejecting a negative number block, representing the ValueError math domain error.

In mathematics, the “domain” of a function is the set of all valid inputs. When a calculation attempts to use a value outside this domain, you may encounter a ValueError math domain error.

  • The domain of “division” is all numbers except zero.
  • The domain of “square root” is all non-negative numbers (0 or higher).

This error means: You gave a function a number that is not in its domain.

The Cause

The most common cause is trying to take the square root (math.sqrt) or logarithm (math.log) of a negative number.

Problem Code:

import math

user_input = -10
# CRASH! You can't take the square root of a negative number
result = math.sqrt(user_input)

Error: ValueError: math domain error

The Fix 1: Check the Input First (LBYL)

The best practice is to check your number before passing it to the function.

import math
user_input = -10

if user_input >= 0:
    result = math.sqrt(user_input)
else:
    print("Cannot calculate square root of a negative number.")
    result = None

The Fix 2: Use cmath (If you need Complex Numbers)

What if you want to handle imaginary numbers? Python has a different module for that: cmath (complex math).

import cmath

user_input = -10
# This works! It returns an imaginary number
result = cmath.sqrt(user_input) 

print(result)
# Output: 3.1622776601683795j

Use math for real-world numbers and cmath for scientific or complex number calculations.

Similar Posts

Leave a Reply