C# Reference ยท Types and Literals
The Complex struct
Reference for System.Numerics.Complex in C#: constructing complex numbers, arithmetic, magnitude and phase, polar form and common functions.
Complex (namespace System.Numerics) represents a complex number a + bi with two double parts: Real and Imaginary. It is a small immutable struct with overloaded operators, so complex arithmetic looks like normal arithmetic.
Complex numbers appear in signal processing, electrical engineering, fractals and anything that deals with rotations in the plane. The type also offers the common functions: Abs, Sqrt, Exp, Pow, Sin, Cos and friends.
using System.Numerics; var z = new Complex(3, 4); Console.WriteLine(z.Magnitude);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public readonly struct Complex : IEquatable<Complex>, IFormattable, INumberBase<Complex> public Complex(double real, double imaginary)
| Member | Description |
|---|---|
Real, Imaginary |
The two parts, both double. |
Magnitude |
Distance from the origin, sqrt(Real^2 + Imaginary^2). |
Phase |
Angle in radians, from -pi to pi. |
Zero, One, ImaginaryOne |
Constants. |
FromPolarCoordinates(magnitude, phase) |
Builds a value from polar form. |
Conjugate(z), Reciprocal(z), Negate(z) |
Unary operations. |
Abs, Sqrt, Exp, Log, Pow, Sin, Cos, Tan, ... |
Functions that return a Complex (Abs returns double). |
Returns: a new Complex, except Abs and the properties.
Errors: none thrown for arithmetic. Division by zero yields infinity or NaN parts rather than an exception.
Usage notes
- Doubles inside. Results carry normal floating-point rounding errors; round before printing or compare with a tolerance, as the polar example does.
- Implicit conversions.
double,int,longand other numeric types convert implicitly toComplexwith an imaginary part of zero. There is no conversion back; readReal. - Default text format.
ToString()prints<real; imaginary>. Pass a numeric format such as"F2"and anIFormatProvider(useCultureInfo.InvariantCulture) to control the parts. - Equality.
==compares both parts exactly. Two values that look equal after calculations may differ in the last bits. - Square roots.
Complex.Sqrtof a negative real number gives the principal root with a positive imaginary part. - Performance. It is a 16-byte struct; arrays of
Complexare contiguous and fast enough for FFT-style code, but there is no SIMD acceleration. - Single precision. There is no
Complex32; convert to and fromfloatyourself.