我相信17个小数位应该足够正确地表示一个8字节的浮点数,这样它是往返安全的(转换成字符串并返回而不会丢失任何内容)。在
但是在这个测试中,这个数字可以高达23,如果增加迭代次数,可能会更高。在
这是一个有缺陷的测试吗?为什么?
如何确保Python中float的往返完整性?在
def TestLoop():
sFormat = ''
success = True
ff = [1.0/i for i in range(1,10000000)]
for n in range(17, 31):
sFormat = '{{:.{:d}f}}'.format(n)
success = True
for f in ff:
if f != float(sFormat.format(f)):
success = False
break
if success:
return(n)
return(-1)
n = TestLoop()
print('Lossless with ', n, ' decimal places.')
在我最初的测试中,我使用的是小数字,所以有很多前导零,它们不是有效数字。浮点数需要17个有效的数字才能正确表示。通过像这样改变一行,我使数字变大,并且只在小数点后16位就成功了。在
最好的方法似乎根本不使用}。
^{pr2}$format()
,而是使用repr()
或{这里的代码成功:
另一种有效的方法是在小数点后使用17位数字,但是使用
g
格式设置程序而不是f
。这使用一个指数,因此前导零被消除。在相关问题 更多 >
编程相关推荐