简体   繁体   English

Python “十进制” package 给出错误的结果

[英]Python “decimal” package gives wrong results

I tried to compute the following by setting getcontext().prec = 800 .我试图通过设置getcontext().prec = 800来计算以下内容。

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

But the expected result is 2 .但预期结果是2 Where am I doing wrong?我在哪里做错了?

The prec attribute defines how many numbers after the decimal point will round your number. prec属性定义了小数点后有多少个数字会将您的数字四舍五入。 For example, if you expect 2.00 , its value should be 3 .例如,如果您期望2.00 ,它的值应该是3 Or if you want to round the number so that it has no decimal places you can use 1 as a parameter.或者,如果您想对数字进行四舍五入,使其没有小数位,您可以使用1作为参数。

from decimal import *

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

When you construct a Decimal from a floating-point number, you get the exact value of the floating-point number, which may not precisely match the decimal value because that's how floating-point numbers work.当您从浮点数构造 Decimal 时,您会得到浮点数的确切值,这可能与十进制值不完全匹配,因为浮点数就是这样工作的。

If you want to do precise decimal arithmetic, construct your Decimal objects from strings instead of floating-point numbers:如果要进行精确的十进制运算,请从字符串而不是浮点数构造 Decimal 对象:

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

It seems that you have to give numbers as a string to prevent them from being evaluated as floating point.似乎您必须将数字作为字符串提供,以防止它们被评估为浮点数。

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

which gives这使

0.200000000000000011102230246251565404236316680908203125
0.2
2.0

Pass strings to the Decimal constructor instead of floats: Decimal('0.2') gives the result you expect, Decimal(0.2) doesn't.将字符串传递给 Decimal 构造函数而不是浮点数: Decimal('0.2')给出您期望的结果, Decimal(0.2)没有。

This is because:这是因为:

If value is a float, the binary floating point value is losslessly converted to its exact decimal equivalent.如果 value 是浮点数,则二进制浮点值将无损转换为其精确的十进制等效值。 This conversion can often require 53 or more digits of precision.这种转换通常需要 53 位或更多位的精度。 For example, Decimal(float('1.1')) converts to Decimal('1.100000000000000088817841970012523233890533447265625').例如,Decimal(float('1.1')) 转换为 Decimal('1.100000000000000088817841970012523233890533447265625')。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM