Floating-Point Errors and errstate

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

This page targets NumPy 2.5 (2.5.4 was current), and was checked in October 2026. Examples target Python 3.13 or 3.14 and were run on Python 3.13. The examples ran on NumPy 2.5.4. NumPy follows the IEEE 754 standard for binary floating point, so everything below applies to float16, float32 and float64 alike, and most of it to complex numbers.

Floating-point arithmetic does not raise exceptions by default: 1.0 / 0.0 produces inf, 0.0 / 0.0 produces nan, and NumPy reports the event with a RuntimeWarning instead of failing. numpy.errstate lets you choose, per block of code, whether each class of event is ignored, warned about, turned into an exception or passed to a handler. The related integer behaviour is different and is described at the end.

The four error classes and the default state

IEEE 754 defines flags for four conditions that NumPy exposes:

Name Meaning Example

divide

Division of a finite non-zero number by zero, or a function with a pole

np.array([1.0]) / 0 gives inf; np.log(0.0) gives -inf

over

The rounded result is too large to represent

np.array([1e308]) * 10 gives inf

under

The result is too small to represent as a normal number (rounds to zero or a subnormal)

np.array([1e-320]) / 1e10 gives 0.0

invalid

The result is undefined

np.sqrt(np.array([-1.0])) and np.array([0.0]) / 0 give nan

The default state is to warn for divide, over and invalid and to ignore under:

import numpy as np

print(np.geterr())
# {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}

print(np.array([1.0]) / 0)            # [inf]   RuntimeWarning: divide by zero encountered in divide
print(np.array([0.0]) / 0)            # [nan]   RuntimeWarning: invalid value encountered in divide
print(np.float64(1) / np.float64(0))  # inf     RuntimeWarning: divide by zero encountered in scalar divide
print(np.array([1e308]) * 10)         # [inf]   RuntimeWarning: overflow encountered in multiply
print(np.sqrt(np.array([-1.0])))      # [nan]   RuntimeWarning: invalid value encountered in sqrt
print(np.log(np.array([0.0])))        # [-inf]  RuntimeWarning: divide by zero encountered in log

A warning is shown once per code location by Python’s default warning filter, so a second occurrence in a loop is silent. For tests and pipelines, either configure the warnings module (warnings.simplefilter("error") turns every RuntimeWarning into an exception) or set the NumPy state explicitly as described next.

errstate: scoped control

np.errstate is a context manager (and a decorator) that sets the handling for the block and restores the previous state on exit. Each of all, divide, over, under and invalid accepts 'ignore', 'warn', 'raise', 'call' or 'log'.

import numpy as np

# 1. Ignore: you know and accept the result
with np.errstate(divide="ignore", invalid="ignore"):
    print(np.array([1.0, 0.0]) / np.array([0.0, 0.0]))     # [inf nan]

# 2. Raise: turn the event into FloatingPointError
with np.errstate(all="raise"):
    try:
        np.array([1.0]) / 0
    except FloatingPointError as e:
        print("FloatingPointError:", e)   # divide by zero encountered in divide

# 3. Call: pass the event to a handler
def handler(kind, flag):
    print("handler:", kind, flag)         # handler: divide by zero 1

with np.errstate(all="call", call=handler):
    np.array([1.0]) / 0

Source: numpy.errstate

np.errstate can also decorate a function: @np.errstate(divide="ignore"). Prefer it to the global np.seterr, which changes the state for the rest of the current context (it returns the old state so that you can restore it with np.seterr(**old)). A library should never call np.seterr at import time, because that would change the behaviour of every caller. np.geterrcall() returns the handler set by np.seterrcall, None by default.

The raise mode is the best debugging tool

When a NaN appears far downstream, the question is where it started. Running the suspect code under np.errstate(all="raise") stops at the first invalid operation and the traceback points at the offending line. over="raise" and invalid="raise" are the most useful. Note that the scope is an invalid operation that produces NaN from non-NaN input; operations on existing NaN (such as np.nan + 1) are quiet, and ordinary comparisons with NaN do not signal either.

Thread safety and context-local state

Since NumPy 2.0, the floating-point error state is context-local, implemented with a Python contextvars variable, instead of being a hidden per-thread global. Setting np.errstate in one thread or one asyncio task does not leak into another, which was a source of surprising behaviour in earlier versions.

import numpy as np
import threading

def worker():
    print("thread:", np.geterr()["divide"])     # thread: warn

with np.errstate(divide="ignore"):
    t = threading.Thread(target=worker)
    t.start()
    t.join()
    print("main:", np.geterr()["divide"])       # main: ignore

A worker thread starts from the default state, not from its parent’s. If worker threads need a particular state, set it inside the worker. More on threads is on Threads, Free-Threading and Performance.

Avoiding the error instead of hiding it

Silencing a warning is acceptable when you understand the result. Often a better fix is to avoid the invalid operation, which also avoids the cost of producing and cleaning up NaNs. The where= and out= pair of every ufunc (see Universal Functions) skips the masked elements entirely, with no warning.

import numpy as np

num = np.array([1.0, 2.0, 3.0])
den = np.array([2.0, 0.0, 4.0])
safe = np.divide(num, den, out=np.zeros_like(num), where=den != 0)
print(safe)         # [0.5  0.   0.75]

Source: numpy.divide

inf, nan and the helpers that test for them

NaN is not equal to anything, including itself, so x == np.nan is always False. Use the predicates.

import numpy as np

print(np.nan == np.nan)                         # False
print(np.isnan(np.nan), np.isinf(-np.inf))      # True True
print(np.isfinite([1, np.inf, np.nan]))         # [ True False False]
print(np.nan_to_num(np.array([np.nan, np.inf, -np.inf])))
# [ 0.00000000e+000  1.79769313e+308 -1.79769313e+308]
print(np.nanmean([1, np.nan]))                   # 1.0
print(np.signbit(-0.0), np.copysign(1, -0.0))   # True -1.0   negative zero exists

The constants are np.nan, np.inf and np.pi, np.e. NumPy 2.0 removed the aliases np.NaN, np.NAN, np.Inf, np.Infinity, np.infty, np.PINF and np.NINF: use np.nan and np.inf (and -np.inf). Code from older books and tutorials that uses the removed spellings fails with an AttributeError; see Migrating to NumPy 2.x. Ordered comparisons with NaN (np.array([np.nan]) < 1) give False, and the invalid flag is not raised for them in current NumPy.

Comparing floats

Binary floating point cannot represent most decimal fractions exactly, so 0.1 + 0.2 is 0.30000000000000004. Exact equality is therefore rarely what you want.

import numpy as np

print(0.1 + 0.2 == 0.3)                                      # False
print(np.isclose(0.1 + 0.2, 0.3))                            # True
print(np.allclose([0.1 + 0.2], [0.3]))                       # True
print(np.isclose(1e-10, 0.0))                                # True   atol=1e-8 default
print(np.isclose(1e-10, 0.0, atol=1e-12))                    # False
print(np.isclose(np.nan, np.nan), np.isclose(np.nan, np.nan, equal_nan=True))   # False True

Source: numpy.isclose

isclose(a, b, rtol=1e-05, atol=1e-08) tests abs(a - b) <= atol + rtol * abs(b). The test is asymmetric (the tolerance scales with b only) and the absolute term makes it meaningless for values near zero unless you set atol to your problem’s scale. For tests use np.testing.assert_allclose, which reports the mismatches, and choose rtol and atol deliberately. np.array_equal and np.array_equiv compare exactly, and np.array_equal(a, b, equal_nan=True) treats NaN in matching places as equal.

Machine limits: finfo and spacing

np.finfo reports the limits of each floating dtype, and np.iinfo the integer ones.

import numpy as np

print(np.finfo(np.float64).eps)                 # 2.220446049250313e-16   spacing at 1.0
print(np.finfo(np.float32).eps)                 # 1.1920929e-07
print(np.finfo(np.float64).max)                 # 1.7976931348623157e+308
print(np.finfo(np.float64).tiny)                # 2.2250738585072014e-308 smallest normal number
print(np.finfo(np.float64).smallest_subnormal)  # 5e-324
print(np.finfo(np.float16).max)                 # 6.55e+04
print(np.spacing(1.0), np.nextafter(1.0, 2.0))  # 2.220446049250313e-16 1.0000000000000002
print(1e16 + 1 == 1e16)                         # True   the 1 is lost
print(np.float32(16777216) + np.float32(1))     # 1.6777216e+07   float32 cannot count past 2**24

Source: numpy.finfo

eps is the gap between 1.0 and the next float, so relative rounding error is at most about eps / 2. Numbers smaller than tiny are subnormal: they still work but with fewer significant bits, and arithmetic on them can be slower on some CPUs. Casting out of range produces inf with an over warning (np.float32(1e39) and np.float16(70000) are both inf), which makes float16 and float32 easy to overflow in exp, squared sums and variance computations. The scalar dtype table and the promotion rules are on Data Types.

Numerically stable idioms

Many NaN and inf problems come from evaluating a mathematically fine formula in a way that overflows or cancels. NumPy has functions for the common cases.

import numpy as np

print(np.log1p(1e-20), np.log(1 + 1e-20))      # 1e-20 0.0     use log1p near 0
print(np.expm1(1e-20), np.exp(1e-20) - 1)      # 1e-20 0.0     use expm1 near 0

print(np.logaddexp(-1000, -1000))               # -999.3068528194401
# np.log(np.exp(-1000) + np.exp(-1000))         # -inf, with a divide warning (exp underflows to 0)

x = np.array([1000.0, 1001.0])
with np.errstate(all="ignore"):
    print(np.exp(x) / np.exp(x).sum())          # [nan nan]   exp(1000) overflows to inf

z = x - x.max()                                 # softmax: subtract the maximum first
print(np.exp(z) / np.exp(z).sum())              # [0.26894142 0.73105858]

The softmax rewrite is the standard fix: subtracting the maximum does not change the result of the ratio but keeps every exponent at or below zero. scipy.special provides logsumexp and softmax that already do this. Other stable helpers are np.hypot (square root of a sum of squares without intermediate overflow), np.cbrt and math.fsum for accurate summation of a list. For summation accuracy in arrays, see Reductions and Axis Semantics.

Integers do not follow these rules

Integer arithmetic has no inf or NaN, so NumPy has no flag to set. What happens instead depends on whether you work on a scalar or an array.

import numpy as np

print(np.int32(2**31 - 1) + np.int32(1))
# -2147483648   RuntimeWarning: overflow encountered in scalar add
print(np.array([2**31 - 1], dtype=np.int32) + 1)
# [-2147483648]   no warning: array integer overflow wraps silently
print(np.array([10]) ** 20)
# [7766279631452241920]   silently wrapped, the true value is 1e20
print(np.array([1, 2]) // 0, np.array([1, 2]) % 0)
# [0 0] [0 0]   RuntimeWarning: divide by zero encountered in floor_divide

print(np.array([300]).astype(np.uint8))
# [44]   300 modulo 256, no warning

Scalar integer overflow warns while array overflow is silent, a long-standing asymmetry. The rules for the type of the result are on Type Promotion; in NumPy 2 a Python integer that does not fit the array’s dtype raises OverflowError instead of wrapping (np.int8(1) + 1000). Integer division or remainder by zero gives 0 with a divide warning, which is also controlled by np.errstate(divide=...). When values might exceed the range, widen the dtype first (astype(np.int64) or dtype= in reductions), use np.iinfo to check the limits, or use Python integers (dtype=object) for exact big-integer arithmetic.

Casting NaN and inf to integers

Casting a non-finite or out-of-range float to an integer is undefined in C, and NumPy reports it with an invalid warning (invalid value encountered in cast). The result is platform-dependent, so never rely on it.

import numpy as np
import warnings

with warnings.catch_warnings():
    warnings.simplefilter("error")
    try:
        np.array([np.nan]).astype(int)
    except RuntimeWarning as e:
        print("RuntimeWarning:", e)       # invalid value encountered in cast

Handle missing values before casting: np.nan_to_num, a boolean mask, or masked arrays (Masked Arrays). Integer arrays cannot hold NaN at all, which is why pandas introduced nullable integer dtypes.

Pitfalls summary

  • NumPy does not raise on x / 0 for floats; it returns inf or nan and warns once per location. Use np.errstate(all="raise") to find the source.

  • np.errstate is scoped and, since NumPy 2.0, context-local; new threads start from the default state. Do not call np.seterr in a library.

  • where= without out= leaves uninitialised data, so combine it with out= when you avoid invalid operations.

  • Test floats with np.isclose and set atol for values near zero; never write x == np.nan.

  • Array integer overflow and out-of-range casts to small integers wrap silently; scalar integer overflow warns.

  • np.NaN, np.Inf and np.infty no longer exist in NumPy 2.

  • In float32 and float16, choose a wider accumulator, subtract the maximum before exp, and use log1p, expm1 and logaddexp.