对Python十进制库感到困惑

问题描述 投票:0回答:1

我正在对Python进行定量分析,与另一位同事比较结果,我们发现由于操作顺序不同,这些典型的浮点数差异在小数点后第17位左右。

寻找解决方案,我找到了十进制库,阅读文档并运行了一些示例

# This is using fixed point arithmetic, resulting on what we would expect
Decimal('0.1') + Decimal('0.2') == Decimal('0.3')

# This is using floating point arithmetic, and thus will never reach 
# the exact number using base 2, the famous 0.30000000000000004
x = 0.1 + 0.2

# But what is this doing? It outputs 0.3000000000000000166533453694, which 
# suggests a floating point usage, but different error
x = Decimal(0.1) + Decimal(0.2) 

所以在这一点上我真的很困惑,为什么这个错误与普通的 python float 不同,如果我想与 Pandas 一起使用这个库,我是否必须将每个操作数转换为 str?

python floating-point decimal precision
1个回答
0
投票

当您使用

Decimal(0.1)
时,您不会得到精确的 0.1,由于通常的浮点不准确,您输入到
Decimal
的常量 0.1 已经关闭 - 请参阅浮点数学是否损坏? 这是 的精确表示一个不准确的数字。当您使用
Decimal('0.1')
时,您 do 会得到精确的 0.1,因为字符串的转换是由
Decimal
本身执行的。

© www.soinside.com 2019 - 2024. All rights reserved.