Python“decimal”包给出错误的结果

2024-06-01 10:57:27 发布

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

我试图通过设置getcontext().prec = 800来计算以下内容

>>> from decimal import *
>>> getcontext().prec = 800
>>> Decimal(22.0) / Decimal ( 10.0) - Decimal ( 0.2 )
Decimal('1.999999999999999988897769753748434595763683319091796875')
>>> 

但预期的结果是2。我哪里做错了


Tags: fromimportdecimalprecgetcontext
3条回答

prec属性定义小数点后有多少个数字将对数字进行四舍五入。例如,如果期望2.00,则其值应为3。或者,如果要将数字四舍五入,使其没有小数位数,可以使用1作为参数

from decimal import *

getcontext().prec = 1
print(Decimal(22.0) / Decimal ( 10.0) - Decimal ( 0.2 ))
>> 2

将字符串传递给十进制构造函数而不是浮点数:Decimal('0.2')给出预期的结果,Decimal(0.2)没有

这是因为:

If value is a float, the binary floating point value is losslessly converted to its exact decimal equivalent. This conversion can often require 53 or more digits of precision. For example, Decimal(float('1.1')) converts to Decimal('1.100000000000000088817841970012523233890533447265625').

https://docs.python.org/3/library/decimal.html#decimal.Decimal

从浮点数构造十进制数时,会得到浮点数的精确值,这可能与十进制数不完全匹配,因为浮点数就是这样工作的

如果要执行精确的十进制算术,请从字符串而不是浮点数构造十进制对象:

>>> Decimal('22.0') / Decimal('10.0') - Decimal('0.2')
Decimal('2.0')

相关问题 更多 >