Decimal.quantize 舍入误差

Decimal.quantize rounding error

我在使用 Decimal 数据类型时偶然发现了量化方法的问题,它似乎给出了舍入错误:

Decimal('1.0055').quantize(Decimal('0.000')) # Should output 1.006
>> Decimal('1.006') # CORRECT output
Decimal('1.0045').quantize(Decimal('0.000')) # Should output 1.005
>> Decimal('1.004') # INCORRECT output

为什么有时向上舍入有时向下舍入?

tl;dr 这就是所谓的bankers' rounding.

默认的舍入模式是

ROUND_HALF_EVEN (to nearest with ties going to nearest even integer)

这正是您所看到的:45 之间以及 56 之间的关系将变为偶数(46)。

如果您想要不同的舍入模式,您需要明确指定。

选项是:

ROUND_CEILING (towards Infinity),
ROUND_DOWN (towards zero),
ROUND_FLOOR (towards -Infinity),
ROUND_HALF_DOWN (to nearest with ties going towards zero),
ROUND_HALF_EVEN (to nearest with ties going to nearest even integer),
ROUND_HALF_UP (to nearest with ties going away from zero), or
ROUND_UP (away from zero).
ROUND_05UP (away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise towards zero)

文档:https://docs.python.org/2/library/decimal.html#decimal.Context

参见 quantize()rounding 参数:https://docs.python.org/2/library/decimal.html#decimal.Decimal.quantize