Python 3.9+Numbers & mathfunction
math.nextafter
representation
The next representable float after x toward y.
Syntax
math.nextafter(...)
Added in Python 3.9; the steps argument only arrived in 3.12. It is the tool for nudging a bound by the smallest possible amount — building a half-open float range, or checking whether two floats are adjacent with nothing representable in between. When x equals y the result is y, and nextafter(0.0, 1.0) returns the smallest positive subnormal, 5e-324.
Examples
import math
print(math.nextafter(1.0, 2.0)) # → 1.0000000000000002
print(math.nextafter(1.0, 0.0)) # → 0.9999999999999999
print(math.nextafter(0.0, 1.0)) # → 5e-324
print(math.nextafter(2.0, 2.0)) # → 2.0
# Python 3.12+
import math
print(math.nextafter(1.0, 2.0, steps=2)) # → 1.0000000000000004
See also
Open in the full glossarydocs.python.orgReport an inaccuracy