Monday, May 31, 2010

Complex Numbers in .net 4.0

Today we are going to discuss about a new type introduced in .net 4.0. This type is Complex. This is a struct type, and is available in System.Numerics namespace. Writing engineering and scientific applications, we encounter complex numbers. Since this was not provided by the framework, we always had to implement in code. Let us start with complex numbers.

As we know that complex numbers can be represented in Cartesian (a, b) and polar coordinates (r, Θ). This number is generally written as follows in scientific calculations:

a + bi

Or in electrical engineering as:

a + jb

Here i or j represents the imaginary part of complex number. As you might know, Euler named it as “imaginary unity”.

The good thing is that the framework supports both representations. Let us start with initialization of complex numbers in both these representations. But before that you would have to add reference of System.Numerics library.

Complex num = newComplex(2, 3);

Complex num2 = Complex.FromPolarCoordinates(5, 0.5);

As you can see that, to declare complex number using polar coordinates, we have to use the static method FromPolarCoordinates().

As we know the following:

a = r CosΘ

b = r SinΘ

Let us write our first piece of code involving complex numbers. In the following code, a complex number is initiated with 3 as its real and 4 as its imaginary part. Then magnitude and phase are printed to see if they have been correctly evaluated.

Let’s verify one of the above calculations. We select multiplication operations:

(1, 2) * (3, 4) = (1 + j2) * (3 + j4)

= 3 + j4 + j6 + (j * j) 8

= 3 + j10 -8 = -5 + j10

Complex numbers might also be compared. Both Equality (= =) and Inequality (!=) operators are overloaded. Additionally, Equals method is overridden. There are basically two versions of Equals(). One is the general one which is available with all .net types (System.Object). The other one is available because Complex structure implements the IEquatable interface.

Complex num1 = newComplex(1, 2);

Complex num2 = newComplex(1, 2);

if (num1 == num2)

Console.WriteLine("num1 == num2 resulted in true condition");

else

Console.WriteLine("num1 == num2 resulted in false condition");

if (num1.Equals(num2))

Console.WriteLine("num1.Equals(num2) resulted in true condition");

else

Console.WriteLine("num1.Equals(num2) resulted in false condition");

This results in the following output:

Complex structure also supports trigonometric functions including regular ones like Sine, Cosine etc. It also supports their inverses, hyperbolics and inverse hyperbolics.

As we predicted, this prints out “Cosine hyperbolic correctly calculated” on the screen.

There are other features provided too like taking conjugate, inverse, logarithm etc. of a complex number. We would not be going in the details about all of them just to save some length of this discussion.