本文介绍了Python“十进制"程序包给出错误结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试通过设置 getcontext().prec = 800
来计算以下内容.
I tried to compute the following by setting getcontext().prec = 800
.
>>> from decimal import *
>>> getcontext().prec = 800
>>> Decimal(22.0) / Decimal ( 10.0) - Decimal ( 0.2 )
Decimal('1.999999999999999988897769753748434595763683319091796875')
>>>
但是预期结果是 2
.我在哪里做错了?
But the expected result is 2
. Where am I doing wrong?
推荐答案
从浮点数构造小数时,您会得到浮点数的确切值,该值可能与十进制值不完全匹配,因为这就是浮点数的工作原理.
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('22.0') / Decimal('10.0') - Decimal('0.2')
Decimal('2.0')
这篇关于Python“十进制"程序包给出错误结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!