Friday, September 9, 2011

Complex Type in Dotnet 4.0


Complex is new numeric type added with Dotnet Framework 4.0. Complex type represents complex numbers and allows us to do some different arithmetic operations. Complex is internally represented as Struct (Value Type). Complex type is available in System.Numerics namespace.

//Complex constructor takes real and imaginary numbers
public Complex(double real, double imaginary);

Let’s understand how to use complex numbers.

Complex c1 = new Complex(1,2);
Console.WriteLine(c1.Real); //Output - 1
Console.WriteLine(c1.Imaginary); //Output - 2
Console.WriteLine(c1.Phase); //Output - 1.10714871779409
Console.WriteLine(c1.Magnitude); //Output - 2.23606797749979

Complex type accepts real and imaginary values with initialization. It exposes four properties Real, Imaginary, Magniture and Phase. As per above code snippet, we created complex type using two values 1 as real value and 2 as imaginary value. Complex type also implements built in operations to do some complex arithmetic operations. It provides Add, Multiply, Subtract, Pow, Exp, Divide, Sin, Cos, Log etc.

Complex c1 = new Complex(5,6);
Complex c2 = new Complex(3,4);

Console.WriteLine("C1 + C2 : "+ Complex.Add(c1, c2)); //Output - (8, 10)
Console.WriteLine("C1 - C2 : " + Complex.Subtract(c1, c2)); //Output - (2, 2)

Above example demonstrates addition and subtraction of two complex types. Complex type provides more complex static methods to do some complex Arithmetic Operations.


See also
BigIntegers in Dotnet 4.0
Covariance and Contravariance in C# 4.0
Dynamic Keyword in C# 4.0

No comments:

Post a Comment