# .Net Framework 4.0: Complex numbers

.Net Framework 4.0 Beta 2 introduces new class in System.Numerics namespace: Complex. Complex represents complex numbers and enables different arithmetic operations with complex numbers. In this posting I will show you how to use complex numbers in .Net Framework 4.0 applications.

Complex class has two constructors – one of them has no arguments and the other takes real and complex parts of complex number. Complex numbers have also properties for phase and magnitude. Let’s see the following code.

static void Main(string[] args){    var z1 = new Complex(); // this creates complex zero (0, 0)    var z2 = new Complex(2, 4);    var z3 = new Complex(3, 5);     Console.WriteLine("Complex zero: " + z1);    Console.WriteLine(z2 + " + " + z3 + " = " + (z2 + z3));     Console.WriteLine("|z2| = " + z2.Magnitude);    Console.WriteLine("Phase of z2 = " + z2.Phase);     Console.ReadLine();}

The output of this code is as follows.

    Complex zero: (0, 0)
(2, 4) + (3, 5) = (5, 9)
|z2| = 4,47213595499958
Phase of z2 = 1,10714871779409

As you can see from output there are some cool things:

• ToString() method of complex number formats complex number like in calculus courses in University (it is called Cartesian form).
• You can use complex numbers like any other numbers and use usual operators on them.

If you feel that this is not good for some reason then you can also use static methods of Complex like Add(), Divide() etc. Following example illustrates how to use methods for calculations.

static void Main(string[] args){    var z2 = new Complex(2, 4);    var z3 = new Complex(3, 5);     var z4 = Complex.Add(z2, z3);    var z5 = Complex.Subtract(z2, z3);    var z6 = Complex.Multiply(z2, z3);    var z7 = Complex.Divide(z2, z3);     Console.WriteLine("z2 + z3 = " + z4);    Console.WriteLine("z2 - z3 = " + z5);    Console.WriteLine("z2 * z3 = " + z6);    Console.WriteLine("z2 / z3 = " + z7);     Console.ReadLine();}

This example produces the following output.

    z2 + z3 = (5, 9)      z2 - z3 = (-1, -1)
z2 * z3 = (-14, 22)
z2 / z3 = (0,764705882352941, 0,0588235294117647)

There are also other mathematical operations defined for complex numbers like trigonometric ones and logarithms, so you can do basically everything you like with complex numbers. I found one thing missing – Parse() and TryParse() methods. Let’s hope these methods are available in stable version of .Net Framework 4.0.