Python Decimal模块一旦达到1.0就停止向另一个Decimal添加Decimals &g



我正在使用python的decimal模块来做一些涉及小数的工作。我有以下代码:

from decimal import *
getcontext().prec = 2  # use two decimal places
counter = Decimal(0)
while counter != Decimal(1000.01):
print(counter)
counter += Decimal(0.01)

这应该以0.01的增量打印从0到1000.00的每个数字,但是由于某种原因,数字0.01到0.09有三位小数(即0.010而不是0.01),当counter达到1.0后(由于某种原因只有一位小数),它就完全停止增长,保持在1.0。输出如下所示:

0
0.010
0.020
0.030
0.040
0.050
0.060
0.070
0.080
0.090
0.10
0.11
0.12
...
0.97
0.98
0.99
1.0
1.0
1.0
(repeats 1.0 forever)

我在这里做错了什么?

Precision指的是位数的个数,而不是计算的小数后的数,所以对于1000.01,您至少需要6。

同样使用字符串来初始化Decimal,因为使用float对于不能很好地以2为基数表示的值来说已经是不准确的了。

的例子:

>>> from decimal import Decimal as d, getcontext
>>> d(0.01)  # don't use float.  It is already inaccurate
Decimal('0.01000000000000000020816681711721685132943093776702880859375')
>>> getcontext().prec  # default precision
28
>>> d(0.01) + d(0.01)
Decimal('0.02000000000000000041633363423')
>>> d('0.01')   # exact!
Decimal('0.01')
>>> getcontext().prec = 6
>>> d(0.01)  # doesn't affect initialization.
Decimal('0.01000000000000000020816681711721685132943093776702880859375')
>>> d(0.01) + d(0.01)  # now the calculation truncates to 6 digits of precision
Decimal('0.0200000')   # note that 2 is the first digit and 00000 are the next 5.
>>> d('0.01') + d('0.01')
Decimal('0.02')

修复了OP示例:

from decimal import *
getcontext().prec = 6  # digits of precision, not really needed...default works too.
counter = Decimal('0')
while counter != Decimal('1000.01'):
print(counter)
counter += Decimal('0.01')