[英]Python, Convert Arbitrary List of Floats to Decimals with Most Precision without Rounding Errors
我正在編寫代碼,它必須在 Python 中采用一堆浮點數並將它們轉換為小數,沒有任何舍入錯誤,但盡可能精確。 我不確定解決這個問題的最佳方法是什么。 僅基於一些經驗測試,這似乎可以正常工作:
import math
from decimal import Decimal
numbers = [2400.2, 4800.3, 3000, 1.1 + 2.2, 0.000000000000006, -1.418686791445350, 1.418686791445356666666, 2400.418686791445350]
def orderOfMagnitude(number):
return math.floor(math.log(abs(number), 10))
for num in numbers:
places = 14 - orderOfMagnitude(num)
dec = Decimal(num).quantize(Decimal(f'1.{"0"*places}'))
print(dec)
輸出:
2400.20000000000
4800.30000000000
3000.00000000000
3.30000000000000
6.00000000000000E-15
-1.41868679144535
1.41868679144536
2400.41868679145
但當然可能有一個反例,這不起作用並且存在錯誤。 例如,如果我在公式中使用 15 而不是 14 來表示我得到的places
:
2400.200000000000
4800.299999999999
3000.000000000000
3.300000000000000
6.000000000000000E-15
-1.418686791445350
1.418686791445357
2400.418686791445
你可以看到4800.3
的錯誤。
以盡可能高的精度將任意浮點數列表轉換為小數而沒有舍入錯誤的正確方法是什么? 這甚至可能嗎?
編輯:如果有區別的話,我在 Windows 10 和 Python 3.8 上。
import math
from decimal import Decimal
numbers = [2400.2, 4800.3, 3000, 1.1 + 2.2, 0.000000000000006, -1.418686791445350, 1.418686791445356666666, 2400.418686791445350]
def orderOfMagnitude(number):
return math.floor(math.log(abs(number), 10))
for num in numbers:
places = 15 - orderOfMagnitude(num)
dec = Decimal(num).quantize(Decimal(f'1.{"0"*places}'))
print(dec)
效果很好
2400.200000000000
4800.300000000000
3000.000000000000
3.300000000000000
6.000000000000000E-15
-1.418686791445350
1.418686791445357
2400.418686791445
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.