为什么小数之和仍然有浮点数错误?

why does sum of decimals still have floating point errors?

我正在使用小数模块来尝试避免浮点错误。从 decimal 模块的纪录片中说:

Decimal numbers can be represented exactly. In contrast, numbers like 1.1 and 2.2 do not have exact representations in binary floating point. End users typically would not expect 1.1 + 2.2 to display as 3.3000000000000003 as it does with binary floating point.

但是当我尝试用小数求和时,我仍然会遇到浮点数错误。

decimal.Decimal(4.04)+decimal.Decimal(4.04)
>>Decimal('8.080000000000000071054273576')

这是为什么?

尝试在浮点文字周围放置字符串,如下所示:

decimal.Decimal('4.04')+decimal.Decimal('4.04')

在您问题的代码中,原始二进制文件(基数 2)"float" 类型被传递给 Decimal。例如,当您使用字符串表示数字 4.04 时,Decimal 精确地表示以 10 为基数的 '4.04'