In python tutorial for floating point,
In base 2, 1/10 is the infinitely repeating fraction
0.0001100110011001100110011001100110011001100110011...
How do I get python interpreter to print this intenal representation? repr(0.1)
does not help.
In python tutorial for floating point,
In base 2, 1/10 is the infinitely repeating fraction
0.0001100110011001100110011001100110011001100110011...
How do I get python interpreter to print this intenal representation? repr(0.1)
does not help.
You can use the struct module to get the internal representation of float. Once you get the representation, you just need to convert the character to the ordinal value and format it to binary.
>>> import struct
>>> def float_rep(num):return ''.join("{:08b}".format(ord(elem)) for elem in struct.pack('!f', num))>>> float_rep(0.1)
'00111101110011001100110011001101'
Edit
Though the above would provide you the actual representation internally, but I suppose, you are more interested in the binary equivalent of the decimal. The following would suffice your query
>>> def float_to_bin(num):sign = '-' if num < 0 else ''num = abs(num)whole = int(num)num -= wholeyield sign + bin(whole) + '.'while num:num*= 2whole = int(num)yield str(whole)num -= whole>>> ''.join(islice(float_to_bin(1.1),None,20))
'1.0001100110011001100'
>>> ''.join(islice(float_to_bin(-1.1),None,20))
'-1.0001100110011001100'
>>> ''.join(islice(float_to_bin(.1),None,20))
'0.0001100110011001100'
>>> ''.join(islice(float_to_bin(0),None,20))
'0.'
>>> ''.join(islice(float_to_bin(1),None,20))
'1.'
>>> ''.join(islice(float_to_bin(0.25),None,20))
'0.01'
>>> ''.join(islice(float_to_bin(0.5),None,20))
'0.1'
>>> ''.join(islice(float_to_bin(-0.5),None,20))
'-0.1'