[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

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

Add square roots to the complex number class

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.


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:


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:


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.

// 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.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.