[英]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.