【问题标题】:Behaviour of ROUND_HALF_DOWN , Python 3.9.5, decimal moduleROUND_HALF_DOWN 的行为,Python 3.9.5,十进制模块
【发布时间】:2021-05-29 21:54:55
【问题描述】:

操作系统:fedora 34 工作站、GNU/Linux

我很困惑。在十进制模块documentation section "Rounding modes" 中说,

decimal.ROUND_HALF_DOWN

    Round to nearest with ties going towards zero.

我有一个例子

import decimal
from decimal import Decimal, getcontext

print('----')
getcontext().prec = 4
getcontext().rounding = decimal.ROUND_HALF_DOWN
print(getcontext())
n1 = Decimal('25.2525') + Decimal('0.003')
print(n1)

我期待结果为 25.25,因为 n1 = 25.2555 中的总和结果在千分之一位置有 5,然后必须下降到 0 并且百分之一位置保持不变。

我错了吗?

为什么我会在 25.26 到达那里?

【问题讨论】:

  • 哪个更接近 25.2555:25.26 还是 25.25?这当然不是领带。注意 0.xx55 > 0.xx50
  • 它查看精度之后的所有数字,而不仅仅是下一个数字。

标签: python-3.x linux decimal rounding


【解决方案1】:

上面写着:

四舍五入到最近的平局趋近于零。

在这种特殊情况下,没有平局,因为 25.2555 比 25.25 更接近 25.26。所以它只是四舍五入到最接近的值,即 25.26。

【讨论】:

  • 我没有考虑尾随数字,这让我能够理解问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2010-12-15
  • 2011-08-13
  • 2018-06-29
相关资源
最近更新 更多