python
math_error
ai_generated
true
ValueError: math domain error
ID: python/valueerror-math-domain
92%Fix Rate
92%Confidence
50Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 311 | active | — | — | — |
Root Cause
Math operation with invalid input. sqrt(-1), log(0), asin(2), etc.
genericWorkarounds
-
95% success Validate input before calling: if x > 0: math.log(x)
if x > 0: math.log(x)
-
88% success Use cmath for complex number support: cmath.sqrt(-1) → 1j
import cmath result = cmath.sqrt(-1) # returns 1j
Dead Ends
Common approaches that don't work:
-
Use try/except and return 0
65% fail
Returns wrong result — NaN or special handling is more appropriate
-
Use abs() on all inputs
70% fail
Changes the mathematical meaning — log(abs(x)) != log(x)
Error Chain
Frequently confused with: