在python tutorial for floating point,
在基数2中,1/10是无限重复的分数
... 0.0001100110011001100110011001100110011001100110011
如何让python解释器打印这种内心表示? repr(0.1)
无效。
答案 0 :(得分:8)
您可以使用struct模块获取float的内部表示。获得表示后,您只需将字符转换为序数值并将其格式化为二进制。
>>> import struct
>>> def float_rep(num):
return ''.join("{:08b}".format(ord(elem)) for elem in struct.pack('!f', num))
>>> float_rep(0.1)
'00111101110011001100110011001101'
修改强>
虽然上面会在内部为你提供实际的表示,但我想,你对二进制的等效二进制更感兴趣。以下内容足以使您的查询
>>> def float_to_bin(num):
sign = '-' if num < 0 else ''
num = abs(num)
whole = int(num)
num -= whole
yield sign + bin(whole) + '.'
while num:
num*= 2
whole = 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'
答案 1 :(得分:0)
使用Decimal
模块:
>>> from decimal import Decimal
>>> Decimal(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
答案 2 :(得分:0)
尝试使用decimal
模块
import decimal
decimal.Decimal(0.1)
给出
Decimal('0.1000000000000000055511151231257827021181583404541015625')