Last active
July 26, 2021 13:35
-
-
Save jorenham/412043c30da296af3de6e2b617e39658 to your computer and use it in GitHub Desktop.
Increment a float with the smallest possible value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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