Python "decimal" 包给出了错误的结果
Python "decimal" package gives wrong results
我试图通过设置 getcontext().prec = 800
.
来计算以下内容
>>> from decimal import *
>>> getcontext().prec = 800
>>> Decimal(22.0) / Decimal ( 10.0) - Decimal ( 0.2 )
Decimal('1.999999999999999988897769753748434595763683319091796875')
>>>
但预期的结果是2
。我哪里做错了?
prec
属性定义小数点后有多少个数字四舍五入。例如,如果您期望 2.00
,则其值应为 3
。或者,如果您想对数字进行四舍五入,使其没有小数位,您可以使用 1
作为参数。
from decimal import *
getcontext().prec = 1
print(Decimal(22.0) / Decimal ( 10.0) - Decimal ( 0.2 ))
>> 2
当您从浮点数构造 Decimal 时,您会得到浮点数的精确值,该值可能与十进制值不完全匹配,因为浮点数就是这样工作的。
如果您想进行精确的十进制运算,请从字符串而不是浮点数构造您的 Decimal 对象:
>>> Decimal('22.0') / Decimal('10.0') - Decimal('0.2')
Decimal('2.0')
看来你必须将数字作为字符串给出,以防止它们被计算为浮点数。
from decimal import *
getcontext().prec = 800
print(Decimal(0.2))
print(Decimal('0.2'))
print(Decimal('22.0') / Decimal ('10.0') - Decimal ('0.2' ))
这给出了
0.200000000000000011102230246251565404236316680908203125
0.2
2.0
将字符串而不是浮点数传递给 Decimal 构造函数: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
我试图通过设置 getcontext().prec = 800
.
>>> from decimal import *
>>> getcontext().prec = 800
>>> Decimal(22.0) / Decimal ( 10.0) - Decimal ( 0.2 )
Decimal('1.999999999999999988897769753748434595763683319091796875')
>>>
但预期的结果是2
。我哪里做错了?
prec
属性定义小数点后有多少个数字四舍五入。例如,如果您期望 2.00
,则其值应为 3
。或者,如果您想对数字进行四舍五入,使其没有小数位,您可以使用 1
作为参数。
from decimal import *
getcontext().prec = 1
print(Decimal(22.0) / Decimal ( 10.0) - Decimal ( 0.2 ))
>> 2
当您从浮点数构造 Decimal 时,您会得到浮点数的精确值,该值可能与十进制值不完全匹配,因为浮点数就是这样工作的。
如果您想进行精确的十进制运算,请从字符串而不是浮点数构造您的 Decimal 对象:
>>> Decimal('22.0') / Decimal('10.0') - Decimal('0.2')
Decimal('2.0')
看来你必须将数字作为字符串给出,以防止它们被计算为浮点数。
from decimal import *
getcontext().prec = 800
print(Decimal(0.2))
print(Decimal('0.2'))
print(Decimal('22.0') / Decimal ('10.0') - Decimal ('0.2' ))
这给出了
0.200000000000000011102230246251565404236316680908203125
0.2
2.0
将字符串而不是浮点数传递给 Decimal 构造函数: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