09-05-2013 04:51 PM
I have found that RoundRealToNearestInteger does not always round a value ending in 0.5 correctly. Here are some examples:
int Temp;
Temp = RoundRealToNearestInteger(2.5); // Temp = 2 Should be 3
Temp = RoundRealToNearestInteger(7.5); // Temp = 8 Correct
Temp = RoundRealToNearestInteger(8.5); // Temp = 8 Should be 9
Temp = RoundRealToNearestInteger(8.50000000001); // Temp = 9 Correct
I assume the source of the problem is that some of these values can't be exactly represented in binary and end up being one binary digit less than 0.5. This is shown by the last example where adding a small epsilon gives the correct result.
The only work around I can think of is to manully add an epsilon every time I use this funciton, like this:
Temp = RoundRealToNearestInteger(NumberToRound + 0.0000000001);
Anybody have any better ideas?
Tony G.
09-05-2013 11:52 PM
Apart any other consideration on how numbers are stored in memory (which can influence the effective quantity of the number: your '2.5' could actually be slightly greater or lower than true two-and-a-half), the online help for the function clearly explains what you are seeing (see here😞
Using the round-half-even algorithm, also known as banker's rounding, the function rounds a value with a fractional part of exactly 0.5 to the nearest even number.
09-06-2013 01:59 AM
Hi Tony,
I think you're right in that the issue results from numeric precision, so it's not the fault of RoundRealToNearestInteger...; the only suggestion I can contribute is to replace your value 0.0000000001 with DBL_EPSILON which is the resolution of type double.
09-06-2013 07:37 AM - edited 09-06-2013 07:39 AM
RoundRealToNearestInteger() uses "banker's rounding" which rounds any value ending in .5 to the nearest even number, not up. This is presumably done to avoid a bias when rounding. Given that, the examples provided appear to be correct.
Edit: Sorry, I see Roberto already pointed this out .
09-06-2013 11:12 AM
I read the function help, but I missed the "even number" part. That seems a bit odd, but at least the funciton is working as described. Thanks for pointing that out!
Tony G.
09-06-2013 03:53 PM
According to this page it's the default rounding rule in IEEE754