Rearrange this to get:
Now we can use the quadratic formula to solve for x2. Recall that the quadratic equation solves the equation Ax2 + Bx + C = 0 and gives the solutions:
In this example, when we replace x with x2 and the values of A, B, and C are:
Plugging those values into the quadratic equation to solve for x2 and taking the positive value for ± gives:
Taking the square root of both sides gives:
If you plug this into the equation for y in terms of x and rearrange a bit, you get:
Now you can multiply by:
The magnitude of a complex number z is defined as:
And b / |b| gives the sign of b, so we can simplify slightly:
This is the version that the code uses. Note that if x + yi is a quare root of the number, then -x - yi is, too.
The following code shows how the example implements the Magnitude and Sqrt properties.
public double Magnitude
return Math.Sqrt(Re * Re + Im * Im);
// Square root.
public Complex Sqrt
double new_re = Math.Sqrt((Magnitude + Re) / 2.0);
double new_im = Math.Sign(Im) * Math.Sqrt((Magnitude - Re) / 2.0);
return new Complex(new_re, new_im);
The Magnitude property squares the numbe's real and imaginary parts, adds them, and takes the square root.
The Sqrt property uses the formulas shown earlier in the Math section to calculate the result's real and imaginary parts. It then uses those values to return a new Complex number.
This property returns one root. Negate its result to find the other.
Download the example to experiment with it and to see additional details.