Python Glossary Русский

Python 3.9+Numbers & mathfunction

math.ulp

representation

The value of the least significant bit (unit in the last place).

Syntax

math.ulp(...)

The gap between neighbouring floats is not constant — it scales with magnitude: around 1.0 it is about 2.2e-16, but around 1e16 it is already 2.0, which is why adding 1 to such a value changes nothing. That is the argument against a fixed epsilon: size your tolerance as a few ulp of the values being compared, or just use math.isclose with its relative tolerance. Available since Python 3.9.

Examples

import math
print(math.ulp(1.0))   # → 2.220446049250313e-16
print(math.ulp(0.0))   # → 5e-324
print(math.ulp(1e16))   # → 2.0
print(1.0 + math.ulp(1.0))   # → 1.0000000000000002
print(1.0 + math.ulp(1.0) / 2 == 1.0)   # → True

See also

Open in the full glossarydocs.python.orgReport an inaccuracy