我相信,小數點後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.')
是的,使用'.17g'作爲格式是正確的方法。 '.16e'也可以。不要在Python 2上使用'str':它沒有提供足夠的數字。但'repr'呢。 (在Python 3的最新版本中,'str'和'repr'對於浮點數是相同的。) –