Skip to content
Test adjacent floating-point boundaries with math.nextafter

Test adjacent floating-point boundaries with math.nextafter

November 24, 2026

A fixed decimal epsilon can skip over many representable values or have no effect at all. Use math.nextafter() to construct the neighboring floating-point values around a threshold.

Run the example

Tested on Linux with Python 3.12.14. No third-party packages or network access are needed. In one Bash session, create a temporary working directory:

demo_start="$PWD"
demo_dir="$(mktemp -d)" || exit 1
cd -- "$demo_dir" || exit 1

Save as demo_float_neighbors.py in that directory. Use this filename to avoid shadowing a standard-library module.

import math

threshold = 1.0
below = math.nextafter(threshold, -math.inf)
above = math.nextafter(threshold, math.inf)
for label, value in (("below", below), ("exact", threshold), ("above", above)):
    print(label, value.hex(), value < threshold, value <= threshold)
print("Upward gap:", above - threshold)
print("Downward gap:", threshold - below)
print("Two steps:", math.nextafter(threshold, math.inf, steps=2).hex())

Run it:

python3 demo_float_neighbors.py

Captured output:

below 0x1.fffffffffffffp-1 True True
exact 0x1.0000000000000p+0 False True
above 0x1.0000000000001p+0 False False
Upward gap: 2.220446049250313e-16
Downward gap: 1.1102230246251565e-16
Two steps: 0x1.0000000000002p+0

Interpret the result

These neighboring values exercise both sides of the comparison without inventing a tolerance. Around 1.0, the upward and downward gaps differ because the binary exponent changes at that boundary. The steps parameter requires Python 3.12. This is a test-data tool, not a replacement for a domain-specific tolerance or decimal arithmetic. Decide separately how your application handles NaN and infinities. The hexadecimal representation exposes the binary values; the captured output uses this Linux interpreter’s floating-point representation.

See the version-specific Python reference for the API contract.

Clean up

In the same Bash session, remove the source file and then the empty working directory:

rm -- demo_float_neighbors.py
cd -- "$demo_start" || exit 1
rmdir -- "$demo_dir"
unset demo_start demo_dir

If the directory is not empty, inspect its remaining contents before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on