Showing posts with label math. Show all posts
Showing posts with label math. Show all posts

Friday, December 17, 2010

Odd Math.Round() behaviour in Mono (same as .NET?)

I had read on a forum somewhere that Math.Round() rounded to the closest even number. I mentioned this to the guys in #mosa and one mentioned that seems like it would be a bug, as it should go from 4.5 -> 5, rather than the (supposedly) expected 4.5 -> 4, with 4 being the closest even number. Another example is 9.5 -> 10 because 10 is the closest even number (9 is odd).

I wrote a simple method to test this.



using System;

namespace round_test
{
class MainClass
{
public static void Main (string[] args)
{
double x = 0d;

while (x < 5d)
{
Console.WriteLine("actual: " + x.ToString());
Console.WriteLine("rounded: " + Math.Round(x).ToString());

x += 0.1d;
}
}
}
}


The output using mono wasn't very consistent. For instance, 2.5 -> 3 while the rest of the n.5 -> closest even number to n (4.5 -> 4, 3.5 -> 4). (full output here). Odd behaviour, bug??


EDIT: It seems there are two types of rounding, explained on MSDN. The default is banker's rounding.