Last active
March 8, 2021 19:44
-
-
Save gunvirranu/5a857d86d71da10ac9be70c211755d02 to your computer and use it in GitHub Desktop.
Most floats don't end! They're just truncated for display.
This file contains 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 | |
from decimal import * | |
getcontext().prec = 40 | |
x = 1.987654321987654321 | |
h = int.from_bytes(struct.pack(">d", x), "big") | |
f = h & ((1 << 52) - 1) | |
e = (h >> 52) & ((1 << 11) - 1) | |
s = h >> 63 | |
frac_part = sum( | |
((f >> (52 - i)) & 1) * Decimal(2)**(-i) | |
for i in range(1, 53) | |
) | |
val = (-1)**s * (1 + frac_part) * Decimal(2)**(e - 1023) | |
print(repr(x)) | |
print(f"{x:.39f}...") | |
print(val) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment