Increment a Python floating point value by the smallest possible amount

python

Solution

Python 3.9 and above

Starting with Python 3.9, released 2020-10-05, you can use the `math.nextafter` function:

`math.nextafter(x, y)`

Return the next floating-point value after x towards y.

If x is equal to y, return y.

Examples:

`math.nextafter(x, math.inf)` goes up: towards positive infinity.

`math.nextafter(x, -math.inf)` goes down: towards minus infinity.

`math.nextafter(x, 0.0)` goes towards zero.

`math.nextafter(x, math.copysign(math.inf, x))` goes away from zero.

See also `math.ulp()`.

A simpler alternative to `math.copysign(math.inf, x)` is to simply substitute `2*x`.

Problem

How can I increment a floating point value in python by the smallest possible amount? Background: I'm using floating point values as dictionary keys. Occasionally, very occasionally (and perhaps never, but not certainly never), there will be collisions. I would like to resolve these by incrementing the floating point value by as small an amount as possible. How can I do this? In C, I would twiddle the bits of the mantissa to achieve this, but I assume that isn't possible in Python.

Original source

Related problems