Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float Rounding Changes in Ruby 2.4

Ruby 2.4 uses Gaussian rounding to round off floating point numbers.

According to Wikipedia:

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.

However, executing the following code in Ruby 2.4 produces a different output than what is 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 is this so or what am I missing?

like image 790
Noman Ur Rehman Avatar asked Feb 16 '17 08:02

Noman Ur Rehman


1 Answers

In order to apply Gaussian rounding, you have to pass the keyword argument :half.

The keyword argument :half can take either :down or :even and the default behavior is still to round up, just as it was 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.

like image 191
Simon Byrne Avatar answered Oct 12 '22 01:10

Simon Byrne