浮球到弦的往返行程

2024-10-04 11:31:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我相信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.')

If an IEEE 754 double precision is converted to a decimal string with at least 17 significant digits and then converted back to double, then the final number must match the original.


Tags: intrueformatforreturnifwithrange
1条回答
网友
1楼 · 发布于 2024-10-04 11:31:11

在我最初的测试中,我使用的是小数字,所以有很多前导零,它们不是有效数字。浮点数需要17个有效的数字才能正确表示。通过像这样改变一行,我使数字变大,并且只在小数点后16位就成功了。在

ff = [10000000.0/i for i in range(1,10000000)]

最好的方法似乎根本不使用format(),而是使用repr()或{}。
这里的代码成功:

^{pr2}$

另一种有效的方法是在小数点后使用17位数字,但是使用g格式设置程序而不是f。这使用一个指数,因此前导零被消除。在

if f != float('{:.17g}'.format(f)):

相关问题 更多 >