Skip to content

Instantly share code, notes, and snippets.

@jorenham
Last active July 26, 2021 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorenham/412043c30da296af3de6e2b617e39658 to your computer and use it in GitHub Desktop.
Save jorenham/412043c30da296af3de6e2b617e39658 to your computer and use it in GitHub Desktop.
Increment a float with the smallest possible value
import sys
for x in (0.0, 1/10, -1/10, sys.float_info.max, sys.float_info.min, float('inf'), float('-inf'), float('NaN')):
print(f'{x}++ => {float_incr(x)}')
i, xi = 0, float('-inf')
while xi < float('inf'):
x = float_incr(xi)
assert x > xi
xi = x / 2 if x < 0 else x * 2
i += 1
print('\n', f'2**{i} floats')
0.0++ => 5e-324
0.1++ => 0.10000000000000002
-0.1++ => -0.09999999999999999
1.7976931348623157e+308++ => inf
2.2250738585072014e-308++ => 2.225073858507202e-308
inf++ => inf
-inf++ => -1.7976931348623157e+308
nan++ => nan
2**4194 floats
import struct
def float_incr(x: float):
if x == float('inf') or x != x:
# ignore infinite and NaN
return x
x_raw = struct.unpack('>Q', struct.pack('>d', x or 0))[0]
dx_raw = 1 if x >= 0 else -1
return struct.unpack('>d', struct.pack('>Q', x_raw + dx_raw))[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment