简体   繁体   English

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

[英]Python Decimal module stops adding Decimals to another Decimal once it reaches 1.0

I am using python's decimal module to do some work involving decimals.我正在使用 python 的 decimal 模块来做一些涉及小数的工作。 I have the following code:我有以下代码:

from decimal import *
getcontext().prec = 2  # use two decimal places

counter = Decimal(0)
while counter != Decimal(1000.01):
    print(counter)
    counter += Decimal(0.01)

This should print every number from 0 to 1000.00 in increments of 0.01, but for some reason, the numbers 0.01 to 0.09 have three decimal places (ie 0.010 instead of 0.01), and after counter reaches 1.0 (with one decimal place for some reason), it just stops increasing at all and remains at 1.0.这应该以 0.01 的增量打印从 0 到 1000.00 的每个数字,但由于某种原因,数字 0.01 到 0.09 有三位小数(即 0.010 而不是 0.01),并且在counter达到 1.0 之后(由于某种原因有一位小数) ,它只是停止增加并保持在 1.0。 The output looks something like this: output 看起来像这样:

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)

What am I doing wrong here?我在这里做错了什么?

Precision is for number of total digits, not number after the decimal, for calculations , so for 1000.01 you need at least 6.精度是位数,而不是小数点后的数字,用于计算,因此对于 1000.01,您至少需要 6。

Also use strings to initialize a Decimal , because using a float will already be inaccurate for values that aren't nicely represented in base 2.还可以使用字符串来初始化Decimal ,因为使用float对于以 2 为基数的不能很好表示的值来说已经不准确了。

Example:例子:

>>> 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')

Fixes to OP example:修复 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')

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

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