Skip to content

OverflowError: math range error

Error message

                math range error
              

Quick summary

A calculation produced a number too large for Python to represent, often in float operations.

Why this happens

  • Exponentiation with a very large exponent

  • Calculating factorial of a very large number with math.factorial

  • Converting a huge float to an integer

Minimal example

✗ Broken code
import math
result = math.exp(1000)  # OverflowError
✓ Fixed code
import math
try:
    result = math.exp(1000)
except OverflowError:
    result = float('inf')
    print("Result too large, using infinity")

math.exp(1000) overflows the float range. Handle with try/except OverflowError and use infinity as a fallback.

How to diagnose

  • Check the values being used in the calculation

  • Print intermediate results to find where the overflow occurs

  • Consider whether the calculation is correct

How to fix

  • Use a different algorithm that avoids large intermediate values

  • Use the decimal module for high-precision arithmetic

  • Handle the error with try/except OverflowError

How to prevent

  • Validate input ranges before expensive calculations

  • Use logarithms to avoid computing very large numbers directly

Related Resources

Related Glossary

Related Lessons

← Back to language