Ruby 2.4 中的浮点舍入更改

Float Rounding Changes in Ruby 2.4

Ruby 2.4使用高斯舍入对浮点数进行舍入

根据维基百科:

A tie-breaking rule that is less biased (even when the original numbers are positive or negative with unequal probability) is round half to even. By this convention, if the fraction of y is 0.5, then q is the even integer nearest to y. Thus, for example, +23.5 becomes +24, as does +24.5; while −23.5 becomes −24, as does −24.5.

但是,在 Ruby 2.4 中执行以下代码会产生与预期不同的输出。

[1.5, 2.5, 3.5, 4.5, 5.5].each { | num | puts num.round }
# output:
2
3
4
5
6
# expected output(based on Gaussian rounding):
2
2
4
4
6

谁能解释为什么会这样或者我错过了什么?

为了应用高斯舍入,您必须传递关键字参数 :half

关键字参数 :half 可以采用 :down:even,默认行为仍然是向上舍入,就像以前一样。

# ruby 2.4.0-rc1
irb(main):001:0> (2.5).round
# => 3
irb(main):008:0> (2.5).round(half: :down)
# => 2
irb(main):009:0> (2.5).round(half: :even)
# => 2

这个决定的背景在this blog post