Export (0) Print
Expand All

Complex Structure

Represents a complex number.

Namespace:  System.Numerics
Assembly:  System.Numerics (in System.Numerics.dll)

public struct Complex : IEquatable<Complex>, 
	IFormattable

The Complex type exposes the following members.

  NameDescription
Public methodComplexInitializes a new instance of the Complex structure using the specified real and imaginary values.
Top

  NameDescription
Public propertyImaginaryGets the imaginary component of the current Complex object.
Public propertyMagnitudeGets the magnitude (or absolute value) of a complex number.
Public propertyPhaseGets the phase of a complex number.
Public propertyRealGets the real component of the current Complex object.
Top

  NameDescription
Public methodStatic memberAbsGets the absolute value (or magnitude) of a complex number.
Public methodStatic memberAcosReturns the angle that is the arc cosine of the specified complex number.
Public methodStatic memberAddAdds two complex numbers and returns the result.
Public methodStatic memberAsinReturns the angle that is the arc sine of the specified complex number.
Public methodStatic memberAtanReturns the angle that is the arc tangent of the specified complex number.
Public methodStatic memberConjugateComputes the conjugate of a complex number and returns the result.
Public methodStatic memberCosReturns the cosine of the specified complex number.
Public methodStatic memberCoshReturns the hyperbolic cosine of the specified complex number.
Public methodStatic memberDivideDivides one complex number by another and returns the result.
Public methodEquals(Complex)Returns a value that indicates whether the current instance and a specified complex number have the same value.
Public methodEquals(Object)Returns a value that indicates whether the current instance and a specified object have the same value. (Overrides ValueType.Equals(Object).)
Public methodStatic memberExpReturns e raised to the power specified by a complex number.
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public methodStatic memberFromPolarCoordinatesCreates a complex number from a point's polar coordinates.
Public methodGetHashCodeReturns the hash code for the current Complex object. (Overrides ValueType.GetHashCode().)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodStatic memberLog(Complex)Returns the natural (base e) logarithm of a specified complex number.
Public methodStatic memberLog(Complex, Double)Returns the logarithm of a specified complex number in a specified base.
Public methodStatic memberLog10Returns the base-10 logarithm of a specified complex number.
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodStatic memberMultiplyReturns the product of two complex numbers.
Public methodStatic memberNegateReturns the additive inverse of a specified complex number.
Public methodStatic memberPow(Complex, Double)Returns a specified complex number raised to a power specified by a double-precision floating-point number.
Public methodStatic memberPow(Complex, Complex)Returns a specified complex number raised to a power specified by a complex number.
Public methodStatic memberReciprocalReturns the multiplicative inverse of a complex number.
Public methodStatic memberSinReturns the sine of the specified complex number.
Public methodStatic memberSinhReturns the hyperbolic sine of the specified complex number.
Public methodStatic memberSqrtReturns the square root of a specified complex number.
Public methodStatic memberSubtractSubtracts one complex number from another and returns the result.
Public methodStatic memberTanReturns the tangent of the specified complex number.
Public methodStatic memberTanhReturns the hyperbolic tangent of the specified complex number.
Public methodToString()Converts the value of the current complex number to its equivalent string representation in Cartesian form. (Overrides ValueType.ToString().)
Public methodToString(IFormatProvider)Converts the value of the current complex number to its equivalent string representation in Cartesian form by using the specified culture-specific formatting information.
Public methodToString(String)Converts the value of the current complex number to its equivalent string representation in Cartesian form by using the specified format for its real and imaginary parts.
Public methodToString(String, IFormatProvider)Converts the value of the current complex number to its equivalent string representation in Cartesian form by using the specified format and culture-specific format information for its real and imaginary parts.
Top

  NameDescription
Public operatorStatic memberAdditionAdds two complex numbers.
Public operatorStatic memberDivisionDivides a specified complex number by another specified complex number.
Public operatorStatic memberEqualityReturns a value that indicates whether two complex numbers are equal.
Public operatorStatic memberExplicit(BigInteger to Complex)Defines an explicit conversion of a BigInteger value to a complex number.
Public operatorStatic memberExplicit(Decimal to Complex)Defines an explicit conversion of a Decimal value to a complex number.
Public operatorStatic memberImplicit(Byte to Complex)Defines an implicit conversion of an unsigned byte to a complex number.
Public operatorStatic memberImplicit(Double to Complex)Defines an implicit conversion of a double-precision floating-point number to a complex number.
Public operatorStatic memberImplicit(Int16 to Complex)Defines an implicit conversion of a 16-bit signed integer to a complex number.
Public operatorStatic memberImplicit(Int32 to Complex)Defines an implicit conversion of a 32-bit signed integer to a complex number.
Public operatorStatic memberImplicit(Int64 to Complex)Defines an implicit conversion of a 64-bit signed integer to a complex number.
Public operatorStatic memberImplicit(SByte to Complex)Defines an implicit conversion of a signed byte to a complex number.
Public operatorStatic memberImplicit(Single to Complex)Defines an implicit conversion of a single-precision floating-point number to a complex number.
Public operatorStatic memberImplicit(UInt16 to Complex)Defines an implicit conversion of a 16-bit unsigned integer to a complex number.
Public operatorStatic memberImplicit(UInt32 to Complex)Defines an implicit conversion of a 32-bit unsigned integer to a complex number.
Public operatorStatic memberImplicit(UInt64 to Complex)Defines an implicit conversion of a 64-bit unsigned integer to a complex number.
Public operatorStatic memberInequalityReturns a value that indicates whether two complex numbers are not equal.
Public operatorStatic memberMultiplyMultiplies two specified complex numbers.
Public operatorStatic memberSubtractionSubtracts a complex number from another complex number.
Public operatorStatic memberUnaryNegationReturns the additive inverse of a specified complex number.
Top

  NameDescription
Public fieldStatic memberImaginaryOneReturns a new Complex instance with a real number equal to zero and an imaginary number equal to one.
Public fieldStatic memberOneReturns a new Complex instance with a real number equal to one and an imaginary number equal to zero.
Public fieldStatic memberZeroReturns a new Complex instance with a real number equal to zero and an imaginary number equal to zero.
Top

A complex number is a number that comprises a real number part and an imaginary number part. A complex number z is usually written in the form z = x + yi, where x and y are real numbers, and i is the imaginary unit that has the property i2 = -1. The real part of the complex number is represented by x, and the imaginary part of the complex number is represented by y.

The Complex type uses the Cartesian coordinate system (real, imaginary) when instantiating and manipulating complex numbers. A complex number can be represented as a point in a two-dimensional coordinate system, which is known as the complex plane. The real part of the complex number is positioned on the x-axis (the horizontal axis), and the imaginary part is positioned on the y-axis (the vertical axis).

Any point in the complex plane can also be expressed based on its absolute value, by using the polar coordinate system., In polar coordinates, a point is characterized by two numbers:

  • Its magnitude, which is the distance of the point from the origin (that is, 0,0, or the point at which the x-axis and the y-axis intersect).

  • Its phase, which is the angle between the real axis and the line drawn from the origin to the point.

Instantiating a Complex Number

You can assign a value to a complex number in one of the following ways:

  • By passing two Double values to its constructor. The first value represents the real part of the complex number, and the second value represents its imaginary part. These values represent the position of the complex number in the two-dimensional Cartesian coordinate system.

  • By calling the static (Shared in Visual Basic) Complex.FromPolarCoordinates method to create a complex number from its polar coordinates.

  • By assigning a Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, or Double value to a Complex object. The value becomes the real part of the complex number, and its imaginary part equals 0.

  • By casting (in C#) or converting (in Visual Basic) a Decimal or BigInteger value to a Complex object. The value becomes the real part of the complex number, and its imaginary part equals 0.

  • By assigning the complex number that is returned by a method or operator to a Complex object. For example, Complex.Add is a static method that returns a complex number that is the sum of two complex numbers, and the Complex.Addition operator adds two complex numbers and returns the result.

The following example demonstrates each of these five ways of assigning a value to a complex number.


using System;
using System.Numerics;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      // Create a complex number by calling its class constructor.
      Complex c1 = new Complex(12, 6);
      outputBlock.Text += c1 + "\n";

      // Assign a Double to a complex number.
      Complex c2 = 3.14;
      outputBlock.Text += c2 + "\n";

      // Cast a Decimal to a complex number.
      Complex c3 = (Complex)12.3m;
      outputBlock.Text += c3 + "\n";

      // Assign the return value of a method to a Complex variable.
      Complex c4 = Complex.Pow(Complex.One, -1);
      outputBlock.Text += c4 + "\n";

      // Assign the value returned by an operator to a Complex variable.
      Complex c5 = Complex.One + Complex.One;
      outputBlock.Text += c5 + "\n";

      // Instantiate a complex number from its polar coordinates.
      Complex c6 = Complex.FromPolarCoordinates(10, .524);
      outputBlock.Text += c6 + "\n";
   }
}
// The example displays the following output:
//       (12, 6)
//       (3.14, 0)
//       (12.3, 0)
//       (1, 0)
//       (2, 0)
//       (8.65824721882145, 5.00347430269914)


Operations with Complex Numbers

The Complex structure in the .NET Framework includes members that provide the following functionality:

  • Methods to compare two complex numbers to determine whether they are equal.

  • Operators to perform arithmetic operations on complex numbers. Complex operators enable you to perform addition, subtraction, multiplication, division, and unary negation with complex numbers.

  • Methods to perform other numerical operations on complex numbers. In addition to the four basic arithmetic operations, you can raise a complex number to a specified power, find the square root of a complex number, and get the absolute value of a complex number.

  • Methods to perform trigonometric operations on complex numbers. For example, you can calculate the tangent of an angle represented by a complex number.

Precision and Complex Numbers

The real and imaginary parts of a complex number are represented by two double-precision floating-point values. This means that Complex values, like double-precision floating-point values, can lose precision as a result of numerical operations. This means that strict comparisons for equality of two Complex values may fail, even if the difference between the two values is due to a loss of precision. For more information, see Double.

For example, performing exponentiation on the logarithm of a number should return the original number. However, in some cases, the loss of precision of floating-point values can cause slight differences between the two values, as the following example illustrates.


Complex value = new Complex(Double.MinValue / 2, Double.MinValue / 2);
Complex value2 = Complex.Exp(Complex.Log(value));
outputBlock.Text += String.Format("{0} \n{1} \nEqual: {2}", value, value2,
                                            value == value2) + "\n";
// The example displays the following output:
//    (-8.98846567431158E+307, -8.98846567431158E+307)
//    (-8.98846567431161E+307, -8.98846567431161E+307)
//    Equal: False


Complex Numbers, Infinity, and NaN

The real and imaginary parts of a complex number are represented by Double values. In addition to ranging from Double.MinValue to Double.MaxValue, the real or imaginary part of a complex number can have a value of Double.PositiveInfinity, Double.NegativeInfinity, or Double.NaN. Double.PositiveInfinity, Double.NegativeInfinity, and Double.NaN all propagate in any arithmetic or trigonometric operation.

In the following example, division by Zero produces a complex number whose real and imaginary parts are both Double.NaN. As a result, performing multiplication with this value also produces a complex number whose real and imaginary parts are Double.NaN. Similarly, performing a multiplication that overflows the range of the Double type produces a complex number whose real part is Double.NaN and whose imaginary part is Double.PositiveInfinity. Subsequently performing division with this complex number returns a complex number whose real part is Double.NaN and whose imaginary part is Double.PositiveInfinity.


using System;
using System.Numerics;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      Complex c1 = new Complex(Double.MaxValue / 2, Double.MaxValue / 2);

      Complex c2 = c1 / Complex.Zero;
      outputBlock.Text += c2.ToString() + "\n";
      c2 = c2 * new Complex(1.5, 1.5);
      outputBlock.Text += c2.ToString() + "\n";
      outputBlock.Text += "\n";

      Complex c3 = c1 * new Complex(2.5, 3.5);
      outputBlock.Text += c3.ToString() + "\n";
      c3 = c3 + new Complex(Double.MinValue / 2, Double.MaxValue / 2);
      outputBlock.Text += c3 + "\n";
   }
}
// The example displays the following output:
//       (NaN, NaN)
//       (NaN, NaN)
//       (NaN, Infinity)
//       (NaN, Infinity)


Mathematical operations with complex numbers that are invalid or that overflow the range of the Double data type do not throw an exception. Instead, they return a Double.PositiveInfinity, Double.NegativeInfinity, or Double.NaN under the following conditions:

Note that this applies to any intermediate calculations performed by a method. For example, the multiplication of new Complex(9e308, 9e308) and new Complex(2.5, 3.5) uses the formula (ac - bd) + (ad + bc)i. The calculation of the real component that results from the multiplication evaluates the expression 9e308 * 2.5 - 9e308 * 3.5. Each intermediate multiplication in this expression returns Double.PositiveInfinity, and the attempt to subtract Double.PositiveInfinity from Double.PositiveInfinity returns Double.NaN.

Formatting a Complex Number

By default, the string representation of a complex number takes the form (real, imaginary), where real and imaginary are the string representations of the Double values that form the complex number's real and imaginary components. Some overloads of the ToString method allow customization of the string representations of these Double values to reflect the formatting conventions of a particular culture or to appear in a particular format defined by a standard or custom numeric format string. (For more information, see Standard Numeric Format Strings and Custom Numeric Format Strings.)

One of the more common ways of expressing the string representation of a complex number takes the form a + bi, where a is the complex number's real component, and b is the complex number's imaginary component. In electrical engineering, a complex number is most commonly expressed as a + bj. You can return the string representation of a complex number in either of these two forms. To do this, define a custom format provider by implementing the ICustomFormatter and IFormatProvider interfaces, and then call the String.Format(IFormatProvider, String, Object[]) method.

The following example defines a ComplexFormatter class that represents a complex number as a string in the form of either a + bi or a + bj.


using System;
using System.Numerics;

public class ComplexFormatter : IFormatProvider, ICustomFormatter
{
   public object GetFormat(Type formatType)
   {
      if (formatType == typeof(ICustomFormatter))
         return this;
      else
         return null;
   }

   public string Format(string format, object arg,
                        IFormatProvider provider)
   {
      if (arg is Complex)
      {
         Complex c1 = (Complex)arg;
         // Check if the format string has a precision specifier.
         int precision;
         string fmtString = String.Empty;
         if (format.Length > 1)
         {
            try
            {
               precision = Int32.Parse(format.Substring(1));
            }
            catch (FormatException)
            {
               precision = 0;
            }
            fmtString = "N" + precision.ToString();
         }
         if (format.Substring(0, 1).Equals("I", StringComparison.OrdinalIgnoreCase))
            return c1.Real.ToString(fmtString) + " + " + c1.Imaginary.ToString(fmtString) + "i";
         else if (format.Substring(0, 1).Equals("J", StringComparison.OrdinalIgnoreCase))
            return c1.Real.ToString(fmtString) + " + " + c1.Imaginary.ToString(fmtString) + "j";
         else
            return c1.ToString(format, provider);
      }
      else
      {
         if (arg is IFormattable)
            return ((IFormattable)arg).ToString(format, provider);
         else if (arg != null)
            return arg.ToString();
         else
            return String.Empty;
      }
   }
}


The following example then uses this custom formatter to display the string representation of a complex number.


public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      Complex c1 = new Complex(12.1, 15.4);
      outputBlock.Text += "Formatting with ToString():       " +
                        c1.ToString() + "\n";
      outputBlock.Text += "Formatting with ToString(format): " +
                        c1.ToString("N2") + "\n";
      outputBlock.Text += "Custom formatting with I0:        " +
                        String.Format(new ComplexFormatter(), "{0:I0}\n", c1);
      outputBlock.Text += "Custom formatting with J3:        " +
                        String.Format(new ComplexFormatter(), "{0:J3}\n", c1);
   }
}
// The example displays the following output:
//    Formatting with ToString():       (12.1, 15.4)
//    Formatting with ToString(format): (12.10, 15.40)
//    Custom formatting with I0:        12 + 15i
//    Custom formatting with J3:        12.100 + 15.400j


Silverlight

Supported in: 5, 4

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Community Additions

ADD
Show:
© 2014 Microsoft