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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With