Skip to content

Instantly share code, notes, and snippets.

@JulienPalard
Created December 12, 2019 14:50
Show Gist options
  • Save JulienPalard/5156d3ae83c8b7cacdaf9e0e5c5b2223 to your computer and use it in GitHub Desktop.
Save JulienPalard/5156d3ae83c8b7cacdaf9e0e5c5b2223 to your computer and use it in GitHub Desktop.
Examine Python's PI
from math import pi
from fractions import Fraction
import struct
def double(bits: str) -> Fraction:
def exponent(input_value: str):
return int(input_value, 2) - 1023
def fraction(b):
return (
sum(Fraction(int(b[i])) * Fraction(2, 2 ** (i + 2)) for i in range(52)) + 1
)
bits = bits.replace(" ", "")
s = int(bits[0], 2)
e = exponent(bits[1:12])
m = fraction(bits[12:])
value = (1 if s == 0 else -1) * m * 2 ** e
return value, s, m, e
value, sign, mantissa, exponent = double(
"".join([f"{x:08b}" for x in struct.pack(">d", pi)])
)
print(
f"""PI, stored as a float is:
mantissa = {mantissa}
exponent = {exponent}
So it's {mantissa} * 2 ** {exponent} which is exactly {value}.
Or : {float(value)}"""
)
# From Wikipedia:
assert (
double("0 01111111111 0000000000000000000000000000000000000000000000000000")[0] == 1
)
assert (
double("0 01111111111 0000000000000000000000000000000000000000000000000001")[0] > 1
)
assert (
double("0 01111111111 0000000000000000000000000000000000000000000000000001")[0]
< 1.0001
)
@JulienPalard
Copy link
Author

mantissa = 884279719003555/562949953421312
exponent = 1

So it's 884279719003555/562949953421312 * 2 ** 1 which is exactly 884279719003555/281474976710656.

Or : 3.141592653589793

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment