Skip to content

Instantly share code, notes, and snippets.

@gunvirranu
Last active March 8, 2021 19:44
Show Gist options
  • Save gunvirranu/5a857d86d71da10ac9be70c211755d02 to your computer and use it in GitHub Desktop.
Save gunvirranu/5a857d86d71da10ac9be70c211755d02 to your computer and use it in GitHub Desktop.
Most floats don't end! They're just truncated for display.
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