小数和舍入函数的工作混乱

Confusion in working of Decimal and Round function

我想了解 Python 的舍入和小数函数的实际工作原理。为此,我尝试 运行 此代码:

from decimal import Decimal print("An integer %i and a float %.1f" %(23, 6.549)) print Decimal(6.549) print Decimal(45.0)/Decimal(7) print Decimal(45.0/7)

我得到了输出:

An integer 23 and a float 6.5
6.54900000000000037658764995285309851169586181640625
6.428571428571428571428571429
6.4285714285714288251938342000357806682586669921875
  1. 我试图从文档here中了解round函数的工作原理,它描述了6.549转换为二进制浮点数并用二进制近似值代替。我对 Decimal(6.549) 的扩展值的近似值从何而来感到困惑。另外,我可以假设每个十进制值的四舍五入都将以相同的方式工作,还是取决于各个二进制近似值?

  2. 当我以两种不同的方式使用 Decimal 函数时,它给出的值略有不同。此外,一个值比另一个值更精确。有人可以说明这是什么原因吗?

提前致谢。

I am confused about where does the approximation in extended value from Decimal(6.549) comes from.

字面量6.549先转为浮点数,以二进制形式存储:由于6.549不能准确存储,因此四舍五入为最接近的值,实际上是

6.54900000000000037658764995285309851169586181640625

(有关详细信息,请参阅 Rick Regan's floating point converter)。

为避免这种中间舍入,请改为传递字符串:

>>> Decimal("6.549")
Decimal('6.549')

Also, can I assume that rounding off of every decimal value will work in the same way or will it depend on the individual binary approximation?

是的,所有数字字面量都会有这个问题(除非可以用二进制精确表示,比如45.07)。

When I use the Decimal function in two different ways, it gives a slightly different value. Also, one value has more precision than the other. Can someone please specify the reason for this?

由于上面的相同问题:Decimal(45.0)/Decimal(7) 将首先将文字 45.07 转换为小数(可以精确完成),然后使用扩展执行除法精度小数库.

另一方面,

Decimal(45.0/7)45.07 都转换为浮点数(准确),但随后以浮点精度执行除法(仅精确到大约 16 位有效数字)。然后将此结果转换为十进制(包括错误的额外数字)。