Created
December 12, 2019 14:50
-
-
Save JulienPalard/5156d3ae83c8b7cacdaf9e0e5c5b2223 to your computer and use it in GitHub Desktop.
Examine Python's PI
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
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 | |
) |
Author
JulienPalard
commented
Dec 12, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment