ML Foundations

Use math.nextafter for adjacent float boundaries

Probe the next representable float around a threshold without confusing it with a decimal step or tolerance.

Example results for Use math.nextafter for adjacent float boundaries. value: 0x1.0000000000000p+0
Illustration: Original illustration by Tensor Almanac
Evidence and testing

Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.

Move by representable values, not decimal increments

`math.nextafter(x, y)` returns a floating-point value after `x` in the direction of `y`; with the default step, it moves to the immediately adjacent representable value. This is useful when a test must examine the boundary just below or above a threshold without guessing a decimal increment such as `1e-15`. [1]

Binary floating-point values are spaced according to their magnitude and representation. `nextafter` asks the runtime for the neighboring value directly, while a tolerance asks whether two numbers are close under a chosen rule. Those solve different testing questions. [1, 2]

References: [1], [2]

Use ulp to inspect the local spacing

`math.ulp(x)` reports the value of the least significant bit at `x`, which gives a useful view of the local representable spacing. The example compares the neighbors around `1.0`: the gap above is twice the gap below because `1.0` lies at a power-of-two boundary in the binary format. [3]

Use `float.hex()` in the fixture to show exact hexadecimal representations. Decimal formatting can hide the one-bit difference that the test is meant to expose. [1, 2]

References: [1], [3]

Apply this to boundary tests carefully

To check an inclusive floating-point cutoff, compare the threshold and its immediate neighbors in the direction relevant to the condition. A test can then state whether the boundary value itself, the next value below, and the next value above should be accepted. [1]

This does not choose a domain tolerance or make a calculation numerically stable by itself. Use it for adjacent-representation cases; choose tolerances from the algorithm and error scale when the requirement is approximate equality. [1, 2]

Executed with Python 3.12.14; stdout captured.

from math import inf, nextafter, ulp

value = 1.0
above = nextafter(value, inf)
below = nextafter(value, -inf)

print("value:", value.hex())
print("next up:", above.hex())
print("next down:", below.hex())
print("ulp(value):", ulp(value).hex())
print("gap above:", above - value)
print("gap below:", value - below)

Recorded output

value: 0x1.0000000000000p+0
next up: 0x1.0000000000001p+0
next down: 0x1.fffffffffffffp-1
ulp(value): 0x1.0000000000000p-52
gap above: 2.220446049250313e-16
gap below: 1.1102230246251565e-16

References: [1], [2]

Sources

  1. Python math nextafter and ulp
  2. Python floating-point tutorial
  3. Python math ulp