math.nextafter(x, y) returns the very next representable floating-point number after x moving toward y.
Added in Python 3.9 (with the optional steps= keyword argument added in Python 3.12), it moves one ULP at a time across IEEE 754 binary64 values—helpful for strict exclusive interval bounds and precision testing.
math.nextafter() is a function in Python's standard math module: import it with import math and call math.nextafter(...), or import the name directly with from math import nextafter. Added in Python 3.9; keyword-only steps parameter added in Python 3.12.
Syntax
Import math and pass start value x and target direction y (Python 3.9+).
python
import math
nxt = math.nextafter(x, y)
k_away = math.nextafter(x, y, steps=3) # Python 3.12+
Call
What it does
math.nextafter(1.0, 2.0)
Returns 1.0000000000000002 (1.0 + 2**-52).
math.nextafter(1.0, 0.0)
Returns 0.9999999999999999 (1.0 - 2**-53).
math.nextafter(0.0, -1.0)
Returns -5e-324 (smallest negative subnormal).
math.nextafter(1.0, 1.0)
Returns 1.0 (unchanged when equal).
Notice stepping upward from 1.0 moves twice as far (2**-52) as stepping downward from 1.0 (2**-53), because exponents change at exact powers of two. See math.ulp().
Function signatures
python
math.nextafter(x, y, /, *, steps=1)
# added in Python 3.9; keyword-only steps= added in Python 3.12
Exponent boundary at 1.0. Values above 1.0 have spacing 2**-52 while values immediately below have spacing 2**-53—half as wide.
Smallest negative subnormal. Stepping down from zero lands on -5e-324 (-2**-1074).
Target infinity means direction. Passing math.inf or -math.inf cleanly picks up or down.
Example 2 — Take Three ULP Steps Portably Across Python 3.9 to 3.12+
Use steps=3 on Python 3.12+ or loop three calls on Python 3.9–3.11.
python
import math
import sys
def step_toward(x, y, count):
if sys.version_info >= (3, 12):
return math.nextafter(x, y, steps=count)
cur = float(x)
for _ in range(count):
cur = math.nextafter(cur, y)
return cur
res = step_toward(1.0, 2.0, 3)
print("3 steps above 1.0:", res)
print("gap in ULPs:", (res - 1.0) / math.ulp(1.0))
Output
3 steps above 1.0: 1.0000000000000007
gap in ULPs: 3.0
Requires Python 3.9 or newer (uses steps= natively on 3.12+).
How It Works
Version check for steps=. Python 3.12+ handles any step count in one C call; older 3.9–3.11 loop step by step.
Exact 3-ULP shift. Dividing the difference by math.ulp(1.0) returns exact 3.0.
Precision testing tool. Useful for checking rounding boundaries and strict open intervals.
Example 3 — Check Equal Inputs, Signed Zeros, and Stepping Down From Inf
See what nextafter() returns at x == y, (0.0, -0.0), and (inf, 0.0).