Strange round() results?

#1

I found that the results of round() are hard to understand:

julia> round(Int, 0.5)
0
julia> round(Int, 1.49999999)
1
julia> round(Int, 1.5)
2
julia> round(Int, 2.5)
2
julia> round(Int, 3.5)
4
julia> round(Int, 4.5)
4
julia> round(Int, 5.5)
6
julia> round(Int, 6.5)
6
0 Likes

#2

See https://docs.julialang.org/en/v1/manual/integers-and-floating-point-numbers/#Rounding-modes-1

0 Likes

#3

It is helpful if you in addition of just listing the results explain what in particular is “hard to understand” and what in the documentation does not explain it well enough.

1 Like

#4

what’s “hard to understand” is:

if round() is rounding-down (floor), 1.5 should get 1, and 2.5 should get 2
otherwise, if it’s rounding-up (ceiling), 1.5 should get 2, and 2.5 should get 3

on the other hand, the “common sense” rounding is: 0 <= x < 0.5 --> 0, 0.5 <= x <= 1.0 --> 1

now, 1.5 gets 2, and 2.5 gets 2 also

it’s counter-intuitive

0 Likes

#5

So the docs for round say

The RoundingMode r controls the direction of the rounding; the default is RoundNearest, which rounds to the nearest integer, with ties (fractional values of 0.5) being rounded to the nearest even integer

And it has your exact example as an example

 Examples
 ≡≡≡≡≡≡≡≡≡≡

  julia> round(1.7)
  2.0

  julia> round(Int, 1.7)
  2

  julia> round(1.5)
  2.0

  julia> round(2.5)
  2.0

See https://en.wikipedia.org/wiki/Rounding#Round_half_to_even:

This is the default rounding mode used in IEEE 754 floating-point operations

3 Likes

#6

Just briefly, the reasoning for this as compared to the rounding that you learned in school is that it removes a bias towards always making numbers farther away from zero. It’s commonly called banker’s rounding for this reason. Imagine you have a sales tax of 10%. Every time you buy something that ends in 5 cents (like 9.95, 11.25, etc), you’re going to need to round to the nearest cent to determine the tax. If you always rounded up, you’d overestimate the tax. If you always rounded down, you’d underestimate it. This tries to remove the bias and it will if your prices are uniformly distributed.

http://wiki.c2.com/?BankersRounding

7 Likes