Rounding Changes in Ruby 2.4

Ruby 2.4 uses Gaussian rounding to round floating point numbers.

According to Wikipedia:

A tie-break rule that is less biased (even when the original numbers are positive or negative with unequal probability) is rounded from half to even. By this convention, if the fraction of y is 0.5, then q is an even integer closest to y. So, for example, +23.5 becomes +24, like +24.5; while -23.5 becomes -24, like -24.5.

However, executing the following code in Ruby 2.4 produces a different result than expected.

[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 

Can someone explain why this is so or what I am missing?

+5
source share
1 answer

To apply Gaussian rounding, you need to pass the keyword argument :half .

The keyword argument :half can take either :down or :even , and the default behavior is still rounded, as before.

 # 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 

The background to this decision is in this blog post .

+7
source

Source: https://habr.com/ru/post/1264289/


All Articles