Index Books FAQ Contact About Rod

# Title: Add square roots to the complex number class in C#

This example adds a square root method to the complex number class described by the example Refine the complex number class in C#.

Be warned that the following section, which explains how to calculate the square root, is pretty mathy. If you don't like math, skip down to the C# code.

# Math

Suppose we have z = a + bi and we want to find x + yi such that:

Squaring both sides gives:

Multiplying this out gives:

Grouping real and imaginary parts gives:

and

Solving this last equation for y gives:

Now we can plug that into the equation for a to get a in terms of x only:

Multiplying both sides by 4x gives:

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:

to get:

So:

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.

# Code

The following code shows how the example implements the Magnitude and Sqrt properties.

// Magnitude. public double Magnitude { get { return Math.Sqrt(Re * Re + Im * Im); } } // Square root. public Complex Sqrt { get { 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.