Showing posts with label floating-point. Show all posts
Showing posts with label floating-point. Show all posts

Thursday, May 31, 2012

Can anyone explain this strange behaviour?


Here is the example with comments:




class Program
{
// first version of structure
public struct D1
{
public double d;
public int f;
}

// during some changes in code then we got D2 from D1
// Field f type became double while it was int before
public struct D2
{
public double d;
public double f;
}

static void Main(string[] args)
{
// Scenario with the first version
D1 a = new D1();
D1 b = new D1();
a.f = b.f = 1;
a.d = 0.0;
b.d = -0.0;
bool r1 = a.Equals(b); // gives true, all is ok

// The same scenario with the new one
D2 c = new D2();
D2 d = new D2();
c.f = d.f = 1;
c.d = 0.0;
d.d = -0.0;
bool r2 = c.Equals(d); // false! this is not the expected result
}
}

Tuesday, May 29, 2012

Why does Math.round(0.49999999999999994) return 1


In the following program you can see that for each value slightly less that .5 is rounded down, except for 0.5.