Last active
December 24, 2015 05:19
-
-
Save mogproject/6749594 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import struct | |
from bitarray import bitarray | |
def double_to_bitstring(d): | |
b = bitarray() | |
b.frombytes(struct.pack('!d', d)) | |
s = b.to01() | |
return '%s %s %s' % (s[0], s[1:12], s[12:]) | |
def bitstring_to_double(bs): | |
return struct.unpack('!d', bitarray(bs).tobytes())[0] | |
def print_header(): | |
print(' ' * 19 + 'sign') | |
print('double'.center(18) + ': v <exponent > < ' + 'significant'.center(48) + ' >') | |
print('=' * 86) | |
def print_double(d): | |
print('%18s: ' % d + double_to_bitstring(d)) | |
if __name__ == '__main__': | |
print_header() | |
print_double(0.0) | |
# 負のゼロというものも存在する | |
print_double(-0.0) | |
print_double(2.0) | |
print_double(3.0) | |
print_double(1.0) | |
# 2進数の小数では有限で表現できないため、誤差が発生する | |
print_double(0.1) | |
# 非数 | |
print_double(float('nan')) | |
# 無限 | |
print_double(float('inf')) | |
print_double(float('-inf')) | |
# 正規化数の限界 | |
print_double(2.225073858507202e-308) | |
print_double(1.7976931348623157e+308) | |
# 非正規化数 | |
print_double(2.225073858507201e-308) | |
print_double(5e-324) | |
# バイナリからの逆引き | |
# print(bitstring_to_double('0' + '0' * 10 + '0' + '0' * 51 + '1')) | |
# print(bitstring_to_double('0' + '0' * 10 + '1' + '0' * 51 + '1')) | |
# print(bitstring_to_double('0' + '1' * 10 + '0' + '1' * 52)) | |
# print(bitstring_to_double('1' + '1' * 10 + '1' + '1' * 52)) | |
# print(bitstring_to_double('1' + '0' * 10 + '1' + '1' + '0' * 51)) | |
# print(bitstring_to_double('1' + '0' * 10 + '0' + '1' + '0' * 51)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment