System.Numerics.Complex 구조체

이 문서에서는 이 API에 대한 참조 설명서에 대한 추가 설명서를 제공합니다.

복소수는 실수 부분과 허수부로 구성된 숫자입니다. 복소수 z는 일반적으로 형식z = x + yi으로 작성됩니다. 여기서 xy는 실수이고, i는 i 2 = -1 속성을 가진 허수 단위입니다. 복소수의 실제 부분은 x표시되고, 복소수의 허수 부분은 y표시됩니다.

이 형식은 Complex 복소수를 인스턴스화하고 조작할 때 카티전 좌표계(실제, 가상)를 사용합니다. 복소수는 복소수 평면이라고 하는 2차원 좌표계의 한 지점으로 나타낼 수 있습니다. 복소수의 실제 부분은 x축(가로 축)에 배치되고 가상 부분은 y축(세로 축)에 배치됩니다.

복소수 평면의 모든 지점은 극좌표계를 사용하여 절대값에 따라 표현할 수도 있습니다. 극좌표에서 점의 특징은 두 가지입니다.

  • 원점(즉, 0,0 또는 x축과 y축이 교차하는 지점)에서 점의 거리인 크기입니다.
  • 실제 축과 원점에서 점까지 그리는 선 사이의 각도인 위상입니다.

복소수 인스턴스화

다음 방법 중 하나로 복소수에 값을 할당할 수 있습니다.

  • 생성자에 두 Double 값을 전달합니다. 첫 번째 값은 복소수의 실제 부분을 나타내고 두 번째 값은 허수 부분을 나타냅니다. 이러한 값은 2차원 카티전 좌표계의 복소수 위치를 나타냅니다.

  • 정적(Shared Visual Basic에서) Complex.FromPolarCoordinates 메서드를 호출하여 극좌표에서 복소수를 만듭니다.

  • 개체에 Byte, , SByte, Int16, UInt16Int32, UInt32, Int64, UInt64Single또는 Double 값을 할당합니다Complex. 값은 복소수의 실제 부분이 되고 허수 부분은 0과 같습니다.

  • C#으로 캐스팅하거나(Visual Basic에서) Decimal 개체 또는 BigInteger 값을 변환합니다 Complex . 값은 복소수의 실제 부분이 되고 허수 부분은 0과 같습니다.

  • 메서드 또는 연산자가 반환하는 복소수를 개체에 할당합니다 Complex . 예를 들어 두 Complex.Add 복소수의 합계인 복소수를 반환하고 Complex.Addition 연산자는 두 개의 복소수를 추가하고 결과를 반환하는 정적 메서드입니다.

다음 예제에서는 복소수에 값을 할당하는 이러한 다섯 가지 방법을 각각 보여 줍니다.

using System;
using System.Numerics;

public class CreateEx
{
    public static void Main()
    {
        // Create a complex number by calling its class constructor.
        Complex c1 = new Complex(12, 6);
        Console.WriteLine(c1);

        // Assign a Double to a complex number.
        Complex c2 = 3.14;
        Console.WriteLine(c2);

        // Cast a Decimal to a complex number.
        Complex c3 = (Complex)12.3m;
        Console.WriteLine(c3);

        // Assign the return value of a method to a Complex variable.
        Complex c4 = Complex.Pow(Complex.One, -1);
        Console.WriteLine(c4);

        // Assign the value returned by an operator to a Complex variable.
        Complex c5 = Complex.One + Complex.One;
        Console.WriteLine(c5);

        // Instantiate a complex number from its polar coordinates.
        Complex c6 = Complex.FromPolarCoordinates(10, .524);
        Console.WriteLine(c6);
    }
}
// The example displays the following output:
//       (12, 6)
//       (3.14, 0)
//       (12.3, 0)
//       (1, 0)
//       (2, 0)
//       (8.65824721882145, 5.00347430269914)
Imports System.Numerics

Module Example
   Public Sub Main()
      ' Create a complex number by calling its class constructor.
      Dim c1 As New Complex(12, 6)
      Console.WriteLine(c1)
      
      ' Assign a Double to a complex number.
      Dim c2 As Complex = 3.14
      Console.WriteLine(c2)
      
      ' Cast a Decimal to a complex number.
      Dim c3 As Complex = CType(12.3d, Complex)
      Console.WriteLine(c3)
      
      ' Assign the return value of a method to a Complex variable.
      Dim c4 As Complex = Complex.Pow(Complex.One, -1)
      Console.WriteLine(c4)
      
      ' Assign the value returned by an operator to a Complex variable.
      Dim c5 As Complex = Complex.One + Complex.One
      Console.WriteLine(c5)

      ' Instantiate a complex number from its polar coordinates.
      Dim c6 As Complex = Complex.FromPolarCoordinates(10, .524)
      Console.WriteLine(c6)
   End Sub
End Module
' The example displays the following output:
'       (12, 6)
'       (3.14, 0)
'       (12.3000001907349, 0)
'       (1, 0)
'       (2, 0)
'       (8.65824721882145, 5.00347430269914)

복소수를 사용하는 작업

.NET의 Complex 구조에는 다음 기능을 제공하는 멤버가 포함됩니다.

  • 두 복소수를 비교하여 같은지 여부를 확인하는 메서드입니다.
  • 복소수에 대한 산술 연산을 수행하는 연산자입니다. Complex 연산자를 사용하면 복소수를 사용하여 더하기, 빼기, 곱하기, 나누기 및 단항 부정을 수행할 수 있습니다.
  • 복소수에 대해 다른 숫자 연산을 수행하는 메서드입니다. 네 가지 기본 산술 연산 외에도 복소수를 지정된 전력으로 올리고, 복소수의 제곱근을 찾고, 복소수의 절대값을 가져올 수 있습니다.
  • 복소수에 대해 삼각 연산을 수행하는 메서드입니다. 예를 들어 복소수로 표시되는 각도의 탄젠트를 계산할 수 있습니다.

Imaginary 속성은 Real 읽기 전용이므로 기존 Complex 개체의 값을 수정할 수 없습니다. 반환 값이 형식Complex인 경우 숫자에 대한 Complex 작업을 수행하는 모든 메서드는 새 Complex 숫자를 반환합니다.

전체 자릿수 및 복소수

복소수의 실제 부분과 가상 부분은 두 개의 배정밀도 부동 소수점 값으로 표시됩니다. 즉 Complex , 배정밀도 부동 소수점 값과 같은 값은 숫자 연산의 결과로 정밀도를 잃을 수 있습니다. 즉, 두 값 간의 차이가 정밀도 손실로 인해 발생하더라도 두 Complex 값의 같음에 대한 엄격한 비교가 실패할 수 있습니다. 자세한 내용은 Double를 참조하세요.

예를 들어 숫자의 로그에서 지수를 수행하면 원래 숫자가 반환됩니다. 그러나 경우에 따라 부동 소수점 값의 전체 자릿수가 손실되면 다음 예제와 같이 두 값 간에 약간의 차이가 발생할 수 있습니다.

Complex value = new Complex(Double.MinValue / 2, Double.MinValue / 2);
Complex value2 = Complex.Exp(Complex.Log(value));
Console.WriteLine("{0} \n{1} \nEqual: {2}", value, value2,
                                            value == value2);
// The example displays the following output:
//    (-8.98846567431158E+307, -8.98846567431158E+307)
//    (-8.98846567431161E+307, -8.98846567431161E+307)
//    Equal: False
Dim value As New Complex(Double.MinValue / 2, Double.MinValue / 2)
Dim value2 As Complex = Complex.Exp(Complex.Log(value))
Console.WriteLine("{0} {3}{1} {3}Equal: {2}", value, value2,
                                              value = value2,
                                              vbCrLf)
' The example displays the following output:
'    (-8.98846567431158E+307, -8.98846567431158E+307)
'    (-8.98846567431161E+307, -8.98846567431161E+307)
'    Equal: False

마찬가지로 숫자의 제곱근을 계산하는 다음 예제는 .NET의 Complex 32비트 및 IA64 버전에서 약간 다른 결과를 생성합니다.

Complex minusOne = new Complex(-1, 0);
Console.WriteLine(Complex.Sqrt(minusOne));
// The example displays the following output:
//    (6.12303176911189E-17, 1) on 32-bit systems.
//    (6.12323399573677E-17,1) on IA64 systems.
Dim minusOne As New Complex(-1, 0)
Console.WriteLine(Complex.Sqrt(minusOne))
' The example displays the following output:
'    (6.12303176911189E-17, 1) on 32-bit systems.
'    (6.12323399573677E-17,1) on IA64 systems.

무한대 및 NaN

복소수의 실제 부분과 허수 부분은 값으로 Double 표시됩니다. 복 Double.MinValueDouble.MaxValue소수의 실제 또는 허수 부분에 범위가 있을 뿐 아니라 , Double.PositiveInfinityDouble.NegativeInfinity또는 Double.NaN값이 있을 수 있습니다. Double.PositiveInfinity, Double.NegativeInfinityDouble.NaN 모든 산술 또는 삼각 연산에서 전파됩니다.

다음 예제에서 나누기 Zero 기준은 실제 부분과 허수 부분이 둘 다 Double.NaN인 복소수를 생성합니다. 따라서 이 값을 곱하면 실제 부분과 허수 부분이 있는 복소수도 생성됩니다 Double.NaN. 마찬가지로 형식의 범위를 오버플로하는 곱셈을 Double 수행하면 실제 부분이 있고 허수 부분이 Double.NaNDouble.PositiveInfinity있는 복소수를 생성합니다. 이후에 이 복소수로 나누기를 수행하면 실제 부분과 허수 부분이 Double.NaNDouble.PositiveInfinity있는 복소수를 반환합니다.

using System;
using System.Numerics;

public class NaNEx
{
    public static void Main()
    {
        Complex c1 = new Complex(Double.MaxValue / 2, Double.MaxValue / 2);

        Complex c2 = c1 / Complex.Zero;
        Console.WriteLine(c2.ToString());
        c2 = c2 * new Complex(1.5, 1.5);
        Console.WriteLine(c2.ToString());
        Console.WriteLine();

        Complex c3 = c1 * new Complex(2.5, 3.5);
        Console.WriteLine(c3.ToString());
        c3 = c3 + new Complex(Double.MinValue / 2, Double.MaxValue / 2);
        Console.WriteLine(c3);
    }
}
// The example displays the following output:
//       (NaN, NaN)
//       (NaN, NaN)
//       (NaN, Infinity)
//       (NaN, Infinity)
Imports System.Numerics

Module Example4
    Public Sub Main()
        Dim c1 As Complex = New Complex(Double.MaxValue / 2, Double.MaxValue / 2)

        Dim c2 As Complex = c1 / Complex.Zero
        Console.WriteLine(c2.ToString())
        c2 = c2 * New Complex(1.5, 1.5)
        Console.WriteLine(c2.ToString())
        Console.WriteLine()

        Dim c3 As Complex = c1 * New Complex(2.5, 3.5)
        Console.WriteLine(c3.ToString())
        c3 = c3 + New Complex(Double.MinValue / 2, Double.MaxValue / 2)
        Console.WriteLine(c3)
    End Sub
End Module
' The example displays the following output:
'       (NaN, NaN)
'       (NaN, NaN)
'
'       (NaN, Infinity)
'       (NaN, Infinity)

유효하지 않거나 데이터 형식의 범위를 오버플로하는 복소수의 Double 수학 연산은 예외를 throw하지 않습니다. 대신 , 또는 Double.NaN 다음 조건에서 반환Double.PositiveInfinityDouble.NegativeInfinity합니다.

이는 메서드에서 수행하는 중간 계산에 적용됩니다. 예를 들어 곱하기 new Complex(9e308, 9e308) and new Complex(2.5, 3.5) 는 수식(ac - bd) + (ad + bc)i를 사용합니다. 곱하기에서 발생하는 실제 구성 요소의 계산은 9e308 2.5 - 9e308 3.5 식을 계산합니다. 이 식의 각 중간 곱셈이 반환되고 반환에서 Double.PositiveInfinityDouble.PositiveInfinity 려는 시도가 반환Double.PositiveInfinity됩니다Double.NaN.

복소수 서식 지정

기본적으로 복소수의 문자열 표현은 실제,가상) 형식(을 사용합니다. 여기서 실수허수는 복소수의 Double 실수 및 허수 구성 요소를 형성하는 값의 문자열 표현입니다. 메서드의 ToString 일부 오버로드를 사용하면 이러한 Double 값의 문자열 표현을 사용자 지정하여 특정 문화권의 서식 규칙을 반영하거나 표준 또는 사용자 지정 숫자 형식 문자열로 정의된 특정 형식으로 표시할 수 있습니다. (자세한 내용은 를 참조하세요 .표준 숫자 형식 문자열 및사용자 지정 숫자 형식 문자열입니다.)

복소수의 문자열 표현을 표현하는 보다 일반적인 방법 중 하나는 + bi 형식을 사용합니다. 여기서 a는 복소수의 실제 구성 요소이고 b는 복소수의 허수 구성 요소입니다. 전기 공학에서 복소수는 가장 일반적으로 + bj로 표현됩니다. 이러한 두 양식 중 하나에서 복소수의 문자열 표현을 반환할 수 있습니다. 이렇게 하려면 및 인터페이스를 구현하여 사용자 지정 형식 공급자를 ICustomFormatterIFormatProvider 정의한 다음 메서드를 호출합니다 String.Format(IFormatProvider, String, Object[]) .

다음 예제에서는 + bi 또는 + bj 형식의 문자열로 복소수를 나타내는 클래스를 정의 ComplexFormatter 합니다.

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;
        }
    }
}
Imports System.Numerics

Public Class ComplexFormatter
    Implements IFormatProvider, ICustomFormatter

    Public Function GetFormat(formatType As Type) As Object _
                    Implements IFormatProvider.GetFormat
        If formatType Is GetType(ICustomFormatter) Then
            Return Me
        Else
            Return Nothing
        End If
    End Function

    Public Function Format(fmt As String, arg As Object,
                           provider As IFormatProvider) As String _
                    Implements ICustomFormatter.Format
        If TypeOf arg Is Complex Then
            Dim c1 As Complex = DirectCast(arg, Complex)
            ' Check if the format string has a precision specifier.
            Dim precision As Integer
            Dim fmtString As String = String.Empty
            If fmt.Length > 1 Then
                Try
                    precision = Int32.Parse(fmt.Substring(1))
                Catch e As FormatException
                    precision = 0
                End Try
                fmtString = "N" + precision.ToString()
            End If
            If fmt.Substring(0, 1).Equals("I", StringComparison.OrdinalIgnoreCase) Then
                Return c1.Real.ToString(fmtString) + " + " + c1.Imaginary.ToString(fmtString) + "i"
            ElseIf fmt.Substring(0, 1).Equals("J", StringComparison.OrdinalIgnoreCase) Then
                Return c1.Real.ToString(fmtString) + " + " + c1.Imaginary.ToString(fmtString) + "j"
            Else
                Return c1.ToString(fmt, provider)
            End If
        Else
            If TypeOf arg Is IFormattable Then
                Return DirectCast(arg, IFormattable).ToString(fmt, provider)
            ElseIf arg IsNot Nothing Then
                Return arg.ToString()
            Else
                Return String.Empty
            End If
        End If
    End Function
End Class

다음 예제에서는 이 사용자 지정 포맷터를 사용하여 복소수의 문자열 표현을 표시합니다.

public class CustomFormatEx
{
    public static void Main()
    {
        Complex c1 = new Complex(12.1, 15.4);
        Console.WriteLine("Formatting with ToString():       " +
                          c1.ToString());
        Console.WriteLine("Formatting with ToString(format): " +
                          c1.ToString("N2"));
        Console.WriteLine("Custom formatting with I0:        " +
                          String.Format(new ComplexFormatter(), "{0:I0}", c1));
        Console.WriteLine("Custom formatting with J3:        " +
                          String.Format(new ComplexFormatter(), "{0:J3}", 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
Module Example2
    Public Sub Main()
        Dim c1 As Complex = New Complex(12.1, 15.4)
        Console.WriteLine("Formatting with ToString():       " +
                          c1.ToString())
        Console.WriteLine("Formatting with ToString(format): " +
                          c1.ToString("N2"))
        Console.WriteLine("Custom formatting with I0:        " +
                          String.Format(New ComplexFormatter(), "{0:I0}", c1))
        Console.WriteLine("Custom formatting with J3:        " +
                          String.Format(New ComplexFormatter(), "{0:J3}", c1))
    End Sub
End Module
' 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