Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is .NET's Complex type broken?

I was astounded to find that the System.Numerics.Complex data type in .NET doesn't yield mathematically accurate results.

Complex.Sqrt(-1) != Complex.ImaginaryOne

Instead of (0, 1), I get (6.12303176911189E-17, 1), which looks a lot like a rounding error.

Now I realize that floating point arithmetic will lead to results like this sometimes, but usually using integers will avoid rounding errors.

Why does this seemingly basic operation yield an obviously wrong result?

like image 774
Kendall Frey Avatar asked Oct 09 '12 19:10

Kendall Frey


1 Answers

Look at the decompiled Sqrt method.

public static Complex Sqrt(Complex value)
{
    return Complex.FromPolarCoordinates(Math.Sqrt(value.Magnitude), value.Phase / 2.0);
}

There is in fact a rounding error caused by using polar coordinates and radians. value.Phase / 2.0 will return pi/2, which isn't an exactly representable number. When converting from polar coordinates (1, pi/2), the rounding error becomes visible when the real coordinate nears zero.

like image 142
Kendall Frey Avatar answered Oct 20 '22 10:10

Kendall Frey