当Decimal()接受字符串而不是float时,为什么精度是准确的?在Python中

2024-03-29 08:01:22 发布

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

为什么这些值不同?它们之间又有什么不同?你知道吗

>>> from decimal import Decimal
>>> Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.3')
Decimal('0.0')

>>> Decimal(0.1) + Decimal(0.1) + Decimal(0.1) - Decimal(0.3)
Decimal('2.775557561565156540423631668E-17')

Tags: fromimportdecimal
2条回答

当您将'0.1'作为字符串传递时,十进制将转换为浮点,而不会丢失精度,但是当您将浮点直接作为0.1传递时,它将丢失精度,如下面所示

>>> Decimal(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> Decimal('0.1')
Decimal('0.1')

这就产生了各种各样的wierd结果

>>> Decimal(0.3) - Decimal(0.1) + Decimal(0.1) + Decimal(0.1)
Decimal('0.3999999999999999944488848768')

这是从十进制模块源代码中引用的,该代码解释得很好,如果输入是float,则模块内部调用class方法十进制浮点数()“:

Note that Decimal.from_float(0.1) is not the same as Decimal('0.1'). Since 0.1 is not exactly representable in binary floating point, the value is stored as the nearest representable value which is 0x1.999999999999ap-4. The exact equivalent of the value in decimal is 0.1000000000000000055511151231257827021181583404541015625.

相关问题 更多 >