Created
October 17, 2020 19:56
-
-
Save constructor-s/347291166a50fca8d4dd7130b9282700 to your computer and use it in GitHub Desktop.
See the representation of a floating point in Python
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 | |
num = 0.5 | |
bits = [[c>>i & 1 for i in range(7, -1, -1)] for c in struct.pack("!d", num)] | |
bits_flatten = [i for l in bits for i in l] | |
bits_sign = bits_flatten[0] | |
bits_exponent = bits_flatten[1:12] | |
bits_fraction = bits_flatten[12:64] | |
sign = (-1) ** bits_sign | |
exponent = sum([b<<i for i, b in enumerate(reversed(bits_exponent))]) - 1023 | |
fraction = 1 + sum([b*(2**(-(i+1))) for i, b in enumerate(bits_fraction)]) | |
print(sign * fraction * (2**exponent)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reference: https://en.wikipedia.org/wiki/Double-precision_floating-point_format