Skip to main content

Fix OverflowError in Python

Error Reference

OverflowError: math range error

A result got too large for a float. Python ints can't overflow — floats can.

Where it comes from

Python integers have arbitrary precision — 2 ** 10_000 just works. OverflowError appears at the boundary with C doubles, which max out near 1.8e308:

import math

math.exp(1000)
# OverflowError: math range error

float(10 ** 400)
# OverflowError: int too large to convert to float

Anything funneling numbers through a float — math functions, float() conversion, struct packing — can hit the limit.

Guard the range

import math, sys

print(sys.float_info.max) # 1.7976931348623157e+308

x = 1000
if x > math.log(sys.float_info.max): # ~709.78
result = math.inf # or clamp / rescale
else:
result = math.exp(x)

Rescaling in log space is the standard fix in statistics and ML — keep values in the log domain and subtract the maximum before exponentiating, so every math.exp argument is at most zero:

import math
a, b = 710.0, 705.0 # log-domain values
m = max(a, b)
lse = m + math.log(math.exp(a - m) + math.exp(b - m))

Working with huge numbers

When you genuinely need magnitudes beyond float range, stay in exact types:

from decimal import Decimal
from fractions import Fraction

Decimal(10) ** 400 # fine — Decimal has its own (huge) limits
Fraction(10) ** 400 # exact rational arithmetic
2 ** 100_000 # plain int: always exact, never overflows

NumPy is different

NumPy uses fixed-width machine types, so it wraps or warns instead of raising — a silent-bug hazard when you come from pure Python:

import numpy as np

np.int32(2_147_483_647) + np.int32(1)
# RuntimeWarning: overflow ... result wraps to -2147483648

Cast to np.int64/np.float64 or plain Python ints where the range matters.

Frequently Asked Questions

Why do Python integers never overflow?

CPython integers are arbitrary-precision objects that grow as needed — there is no fixed 32- or 64-bit box to overflow. The cost is speed and memory, the benefit is exact arithmetic at any size. Overflow only appears when converting to a fixed-size representation like a C double or a NumPy dtype.

What is the largest float Python can hold?

sys.float_info.max, about 1.798e308 (IEEE 754 double precision). Beyond it, operations either raise OverflowError or produce inf, depending on the operation. Literals like 1e400 quietly become inf.

import sys
print(sys.float_info.max) # 1.7976931348623157e+308
print(1e400) # inf

Why does math.exp raise but ** return inf?

The math module wraps C library functions and converts C range errors into OverflowError. Float arithmetic like 1e308 * 10 follows IEEE 754 rules instead and yields inf. It's an inconsistency to know about: guard math.* calls, and check math.isinf() on results of raw float arithmetic.

Next up in your learning path