Complex Struct-datatyp

Definition

Representerar ett komplext tal.

public value class Complex : IEquatable<System::Numerics::Complex>, IFormattable
public value class Complex : IEquatable<System::Numerics::Complex>, IParsable<System::Numerics::Complex>, ISpanParsable<System::Numerics::Complex>, IUtf8SpanParsable<System::Numerics::Complex>, System::Numerics::IAdditionOperators<System::Numerics::Complex, System::Numerics::Complex, System::Numerics::Complex>, System::Numerics::IAdditiveIdentity<System::Numerics::Complex, System::Numerics::Complex>, System::Numerics::IDecrementOperators<System::Numerics::Complex>, System::Numerics::IDivisionOperators<System::Numerics::Complex, System::Numerics::Complex, System::Numerics::Complex>, System::Numerics::IEqualityOperators<System::Numerics::Complex, System::Numerics::Complex, bool>, System::Numerics::IIncrementOperators<System::Numerics::Complex>, System::Numerics::IMultiplicativeIdentity<System::Numerics::Complex, System::Numerics::Complex>, System::Numerics::IMultiplyOperators<System::Numerics::Complex, System::Numerics::Complex, System::Numerics::Complex>, System::Numerics::INumberBase<System::Numerics::Complex>, System::Numerics::ISignedNumber<System::Numerics::Complex>, System::Numerics::ISubtractionOperators<System::Numerics::Complex, System::Numerics::Complex, System::Numerics::Complex>, System::Numerics::IUnaryNegationOperators<System::Numerics::Complex, System::Numerics::Complex>, System::Numerics::IUnaryPlusOperators<System::Numerics::Complex, System::Numerics::Complex>
public value class Complex : IEquatable<System::Numerics::Complex>, IParsable<System::Numerics::Complex>, ISpanParsable<System::Numerics::Complex>, System::Numerics::IAdditionOperators<System::Numerics::Complex, System::Numerics::Complex, System::Numerics::Complex>, System::Numerics::IAdditiveIdentity<System::Numerics::Complex, System::Numerics::Complex>, System::Numerics::IDecrementOperators<System::Numerics::Complex>, System::Numerics::IDivisionOperators<System::Numerics::Complex, System::Numerics::Complex, System::Numerics::Complex>, System::Numerics::IEqualityOperators<System::Numerics::Complex, System::Numerics::Complex, bool>, System::Numerics::IIncrementOperators<System::Numerics::Complex>, System::Numerics::IMultiplicativeIdentity<System::Numerics::Complex, System::Numerics::Complex>, System::Numerics::IMultiplyOperators<System::Numerics::Complex, System::Numerics::Complex, System::Numerics::Complex>, System::Numerics::INumberBase<System::Numerics::Complex>, System::Numerics::ISignedNumber<System::Numerics::Complex>, System::Numerics::ISubtractionOperators<System::Numerics::Complex, System::Numerics::Complex, System::Numerics::Complex>, System::Numerics::IUnaryNegationOperators<System::Numerics::Complex, System::Numerics::Complex>, System::Numerics::IUnaryPlusOperators<System::Numerics::Complex, System::Numerics::Complex>
public struct Complex : IEquatable<System.Numerics.Complex>, IFormattable
public readonly struct Complex : IEquatable<System.Numerics.Complex>, IParsable<System.Numerics.Complex>, ISpanParsable<System.Numerics.Complex>, IUtf8SpanParsable<System.Numerics.Complex>, System.Numerics.IAdditionOperators<System.Numerics.Complex,System.Numerics.Complex,System.Numerics.Complex>, System.Numerics.IAdditiveIdentity<System.Numerics.Complex,System.Numerics.Complex>, System.Numerics.IDecrementOperators<System.Numerics.Complex>, System.Numerics.IDivisionOperators<System.Numerics.Complex,System.Numerics.Complex,System.Numerics.Complex>, System.Numerics.IEqualityOperators<System.Numerics.Complex,System.Numerics.Complex,bool>, System.Numerics.IIncrementOperators<System.Numerics.Complex>, System.Numerics.IMultiplicativeIdentity<System.Numerics.Complex,System.Numerics.Complex>, System.Numerics.IMultiplyOperators<System.Numerics.Complex,System.Numerics.Complex,System.Numerics.Complex>, System.Numerics.INumberBase<System.Numerics.Complex>, System.Numerics.ISignedNumber<System.Numerics.Complex>, System.Numerics.ISubtractionOperators<System.Numerics.Complex,System.Numerics.Complex,System.Numerics.Complex>, System.Numerics.IUnaryNegationOperators<System.Numerics.Complex,System.Numerics.Complex>, System.Numerics.IUnaryPlusOperators<System.Numerics.Complex,System.Numerics.Complex>
public readonly struct Complex : IEquatable<System.Numerics.Complex>, IFormattable
public readonly struct Complex : IEquatable<System.Numerics.Complex>, IParsable<System.Numerics.Complex>, ISpanParsable<System.Numerics.Complex>, System.Numerics.IAdditionOperators<System.Numerics.Complex,System.Numerics.Complex,System.Numerics.Complex>, System.Numerics.IAdditiveIdentity<System.Numerics.Complex,System.Numerics.Complex>, System.Numerics.IDecrementOperators<System.Numerics.Complex>, System.Numerics.IDivisionOperators<System.Numerics.Complex,System.Numerics.Complex,System.Numerics.Complex>, System.Numerics.IEqualityOperators<System.Numerics.Complex,System.Numerics.Complex,bool>, System.Numerics.IIncrementOperators<System.Numerics.Complex>, System.Numerics.IMultiplicativeIdentity<System.Numerics.Complex,System.Numerics.Complex>, System.Numerics.IMultiplyOperators<System.Numerics.Complex,System.Numerics.Complex,System.Numerics.Complex>, System.Numerics.INumberBase<System.Numerics.Complex>, System.Numerics.ISignedNumber<System.Numerics.Complex>, System.Numerics.ISubtractionOperators<System.Numerics.Complex,System.Numerics.Complex,System.Numerics.Complex>, System.Numerics.IUnaryNegationOperators<System.Numerics.Complex,System.Numerics.Complex>, System.Numerics.IUnaryPlusOperators<System.Numerics.Complex,System.Numerics.Complex>
[System.Serializable]
public struct Complex : IEquatable<System.Numerics.Complex>, IFormattable
type Complex = struct
    interface IFormattable
type Complex = struct
    interface IFormattable
    interface IParsable<Complex>
    interface ISpanFormattable
    interface ISpanParsable<Complex>
    interface IAdditionOperators<Complex, Complex, Complex>
    interface IAdditiveIdentity<Complex, Complex>
    interface IDecrementOperators<Complex>
    interface IDivisionOperators<Complex, Complex, Complex>
    interface IEqualityOperators<Complex, Complex, bool>
    interface IIncrementOperators<Complex>
    interface IMultiplicativeIdentity<Complex, Complex>
    interface IMultiplyOperators<Complex, Complex, Complex>
    interface INumberBase<Complex>
    interface IUtf8SpanFormattable
    interface IUtf8SpanParsable<Complex>
    interface ISubtractionOperators<Complex, Complex, Complex>
    interface IUnaryNegationOperators<Complex, Complex>
    interface IUnaryPlusOperators<Complex, Complex>
    interface ISignedNumber<Complex>
type Complex = struct
    interface IFormattable
    interface IParsable<Complex>
    interface ISpanFormattable
    interface ISpanParsable<Complex>
    interface IUtf8SpanFormattable
    interface IUtf8SpanParsable<Complex>
    interface IAdditionOperators<Complex, Complex, Complex>
    interface IAdditiveIdentity<Complex, Complex>
    interface IDecrementOperators<Complex>
    interface IDivisionOperators<Complex, Complex, Complex>
    interface IEqualityOperators<Complex, Complex, bool>
    interface IIncrementOperators<Complex>
    interface IMultiplicativeIdentity<Complex, Complex>
    interface IMultiplyOperators<Complex, Complex, Complex>
    interface INumberBase<Complex>
    interface ISubtractionOperators<Complex, Complex, Complex>
    interface IUnaryNegationOperators<Complex, Complex>
    interface IUnaryPlusOperators<Complex, Complex>
    interface ISignedNumber<Complex>
type Complex = struct
    interface IFormattable
    interface IParsable<Complex>
    interface ISpanFormattable
    interface ISpanParsable<Complex>
    interface IAdditionOperators<Complex, Complex, Complex>
    interface IAdditiveIdentity<Complex, Complex>
    interface IDecrementOperators<Complex>
    interface IDivisionOperators<Complex, Complex, Complex>
    interface IEqualityOperators<Complex, Complex, bool>
    interface IIncrementOperators<Complex>
    interface IMultiplicativeIdentity<Complex, Complex>
    interface IMultiplyOperators<Complex, Complex, Complex>
    interface INumberBase<Complex>
    interface ISubtractionOperators<Complex, Complex, Complex>
    interface IUnaryNegationOperators<Complex, Complex>
    interface IUnaryPlusOperators<Complex, Complex>
    interface ISignedNumber<Complex>
type Complex = struct
    interface IFormattable
    interface IParsable<Complex>
    interface ISpanFormattable
    interface ISpanParsable<Complex>
    interface IAdditionOperators<Complex, Complex, Complex>
    interface IAdditiveIdentity<Complex, Complex>
    interface IDecrementOperators<Complex>
    interface IDivisionOperators<Complex, Complex, Complex>
    interface IEqualityOperators<Complex, Complex, bool>
    interface IIncrementOperators<Complex>
    interface IMultiplicativeIdentity<Complex, Complex>
    interface IMultiplyOperators<Complex, Complex, Complex>
    interface INumberBase<Complex>
    interface ISubtractionOperators<Complex, Complex, Complex>
    interface IUnaryNegationOperators<Complex, Complex>
    interface IUnaryPlusOperators<Complex, Complex>
    interface IUtf8SpanFormattable
    interface IUtf8SpanParsable<Complex>
    interface ISignedNumber<Complex>
[<System.Serializable>]
type Complex = struct
    interface IFormattable
Public Structure Complex
Implements IEquatable(Of Complex), IFormattable
Public Structure Complex
Implements IAdditionOperators(Of Complex, Complex, Complex), IAdditiveIdentity(Of Complex, Complex), IDecrementOperators(Of Complex), IDivisionOperators(Of Complex, Complex, Complex), IEqualityOperators(Of Complex, Complex, Boolean), IEquatable(Of Complex), IIncrementOperators(Of Complex), IMultiplicativeIdentity(Of Complex, Complex), IMultiplyOperators(Of Complex, Complex, Complex), INumberBase(Of Complex), IParsable(Of Complex), ISignedNumber(Of Complex), ISpanParsable(Of Complex), ISubtractionOperators(Of Complex, Complex, Complex), IUnaryNegationOperators(Of Complex, Complex), IUnaryPlusOperators(Of Complex, Complex), IUtf8SpanParsable(Of Complex)
Public Structure Complex
Implements IAdditionOperators(Of Complex, Complex, Complex), IAdditiveIdentity(Of Complex, Complex), IDecrementOperators(Of Complex), IDivisionOperators(Of Complex, Complex, Complex), IEqualityOperators(Of Complex, Complex, Boolean), IEquatable(Of Complex), IIncrementOperators(Of Complex), IMultiplicativeIdentity(Of Complex, Complex), IMultiplyOperators(Of Complex, Complex, Complex), INumberBase(Of Complex), IParsable(Of Complex), ISignedNumber(Of Complex), ISpanParsable(Of Complex), ISubtractionOperators(Of Complex, Complex, Complex), IUnaryNegationOperators(Of Complex, Complex), IUnaryPlusOperators(Of Complex, Complex)
Arv
Complex
Attribut
Implementeringar

Kommentarer

Ett komplext tal är ett tal som består av en verklig taldel och en imaginär taldel. Ett komplext tal z skrivs vanligtvis i formatet z = x + yi, där x och y är verkliga tal, och jag är den imaginära enheten som har egenskapen i2 = -1. Den verkliga delen av det komplexa talet representeras av x, och den imaginära delen av det komplexa talet representeras av y.

Typen Complex använder det kartesiska koordinatsystemet (verkligt, imaginärt) när du instansierar och manipulerar komplexa tal. Ett komplext tal kan representeras som en punkt i ett tvådimensionellt koordinatsystem, vilket kallas för det komplexa planet. Den verkliga delen av det komplexa talet placeras på x-axeln (den vågräta axeln) och den imaginära delen är placerad på y-axeln (den lodräta axeln).

Alla punkter i det komplexa planet kan också uttryckas baserat på dess absoluta värde med hjälp av polarkoordinatsystemet. I polära koordinater kännetecknas en punkt av två tal:

  • Dess storlek, som är avståndet mellan punkten och ursprunget (dvs. 0,0 eller den punkt där x-axeln och y-axeln korsar varandra).
  • Dess fas, som är vinkeln mellan den verkliga axeln och den linje som dras från ursprunget till punkten.

Instansiera ett komplext tal

Du kan tilldela ett värde till ett komplext tal på något av följande sätt:

  • Genom att skicka två Double värden till konstruktorn. Det första värdet representerar den verkliga delen av det komplexa talet och det andra värdet representerar dess imaginära del. Dessa värden representerar positionen för det komplexa talet i det tvådimensionella kartesiska koordinatsystemet.

  • Genom att anropa metoden static (Shared i Visual Basic) Complex.FromPolarCoordinates för att skapa ett komplext tal från dess polära koordinater.

  • Genom att tilldela ett Bytevärde , SByte, Int16, UInt16, Int32, UInt32Int64, UInt64, Singleeller Double till ett Complex objekt. Värdet blir den verkliga delen av det komplexa talet och dess imaginära del är lika med 0.

  • Genom att konvertera (i C#) eller konvertera (i Visual Basic) ett Decimal eller BigInteger -värde till ett Complex objekt. Värdet blir den verkliga delen av det komplexa talet och dess imaginära del är lika med 0.

  • Genom att tilldela det komplexa tal som returneras av en metod eller operator till ett Complex objekt. Är till exempel Complex.Add en statisk metod som returnerar ett komplext tal som är summan av två komplexa tal, och operatorn Complex.Addition lägger till två komplexa tal och returnerar resultatet.

I följande exempel visas vart och ett av dessa fem sätt att tilldela ett värde till ett komplext tal.

using System;
using System.Numerics;

public class CreateEx
{
    public static void Run()
    {
        // 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 Run()
      ' 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)

Åtgärder med komplexa tal

Strukturen Complex i .NET innehåller medlemmar som tillhandahåller följande funktioner:

  • Metoder för att jämföra två komplexa tal för att avgöra om de är lika med.
  • Operatorer för att utföra aritmetiska åtgärder på komplexa tal. Complex med operatorer kan du utföra addition, subtraktion, multiplikation, division och oharisk negation med komplexa tal.
  • Metoder för att utföra andra numeriska åtgärder på komplexa tal. Förutom de fyra grundläggande aritmetiska åtgärderna kan du höja ett komplext tal till en angiven effekt, hitta kvadratroten för ett komplext tal och hämta det absoluta värdet för ett komplext tal.
  • Metoder för att utföra trigonometriska åtgärder på komplexa tal. Du kan till exempel beräkna tangensen för en vinkel som representeras av ett komplext tal.

Observera att eftersom Real egenskaperna och Imaginary är skrivskyddade kan du inte ändra värdet för ett befintligt Complex objekt. Alla metoder som utför en åtgärd på ett Complex tal, om deras returvärde är av typen Complex, returnerar ett nytt Complex tal.

Precision och komplexa tal

De verkliga och imaginära delarna i ett komplext tal representeras av två flyttalsvärden med dubbel precision. Det innebär att Complex värden, till exempel flyttalsvärden med dubbel precision, kan förlora precision till följd av numeriska åtgärder. Det innebär att strikta jämförelser för likhet mellan två Complex värden kan misslyckas, även om skillnaden mellan de två värdena beror på en förlust av precision. Mer information finns i Double.

Om du till exempel utför exponentering på logaritmen för ett tal ska det ursprungliga talet returneras. I vissa fall kan dock förlust av precision för flyttalsvärden orsaka små skillnader mellan de två värdena, vilket visas i följande exempel.

Complex value = new Complex(Double.MinValue / 2, Double.MinValue / 2);
Complex value2 = Complex.Exp(Complex.Log(value));
Console.WriteLine($"{value} \n{value2} \nEqual: {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

På samma sätt ger följande exempel, som beräknar kvadratroten för ett Complex tal, något olika resultat på 32-bitars- och IA64-versionerna av .NET.

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.

Infinity och NaN

De verkliga och imaginära delarna i ett komplext tal representeras av Double värden. Förutom allt från Double.MinValue till Double.MaxValuekan den verkliga eller imaginära delen av ett komplext tal ha värdet Double.PositiveInfinity, Double.NegativeInfinityeller Double.NaN. Double.PositiveInfinity, Double.NegativeInfinity, och Double.NaN propagerar alla i alla aritmetiska eller trigonometriska operationer.

I följande exempel genererar division by Zero ett komplext tal vars verkliga och imaginära delar båda Double.NaNär . Därför ger multiplikation med det här värdet också ett komplext tal vars verkliga och imaginära delar är Double.NaN. På samma sätt genererar en multiplikation som spiller över intervallet av Double typen ett komplext tal vars verkliga del är Double.NaN och vars imaginära del är Double.PositiveInfinity. Därefter returnerar division med det här komplexa talet ett komplext tal vars verkliga del är Double.NaN och vars imaginära del är Double.PositiveInfinity.

using System;
using System.Numerics;

public class NaNEx
{
    public static void Run()
    {
        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 Run()
        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)

Matematiska åtgärder med komplexa tal som är ogiltiga eller som spiller över datatypens intervall Double utlöser inte ett undantag. I stället returnerar de en Double.PositiveInfinity, Double.NegativeInfinity, eller Double.NaN under följande villkor:

Observera att detta gäller för alla mellanliggande beräkningar som utförs av en metod. Till exempel använder multiplikationen av new Complex(9e308, 9e308) and new Complex(2.5, 3.5) formeln (ac - bd) + (ad + bc)i. Beräkningen av den verkliga komponenten som är resultatet av multiplikationen utvärderar uttrycket 9e308 2.5 – 9e308 3.5. Varje mellanliggande multiplikation i det här uttrycket returnerar Double.PositiveInfinityoch försöket att subtrahera Double.PositiveInfinity från Double.PositiveInfinity returnerar Double.NaN.

Formatera ett komplext tal

Som standard tar strängrepresentationen av ett komplext tal formen <verklig; imaginär>, där verkliga och imaginära är strängrepresentationerna av de Double värden som utgör det komplexa talets verkliga och imaginära komponenter. Vissa överlagringar av ToString metoden tillåter anpassning av strängrepresentationer av dessa Double värden så att de återspeglar formateringskonventionerna för en viss kultur eller visas i ett visst format som definieras av en standardsträng eller en anpassad numerisk formatsträng. (Mer information finns i Numeriska standardformatsträngar och anpassade numeriska formatsträngar.)

Ett av de vanligaste sätten att uttrycka strängrepresentationen av ett komplext tal är formen a + bi, där a är det komplexa talets verkliga komponent och b är det komplexa talets imaginära komponent. Inom elektroteknik uttrycks ett komplext tal oftast som a + bj. Du kan returnera strängrepresentationen av ett komplext tal i något av dessa två formulär. Det gör du genom att definiera en anpassad formatprovider genom att implementera gränssnitten ICustomFormatter och IFormatProvider och sedan anropa String.Format(IFormatProvider, String, Object[]) metoden.

I följande exempel definieras en ComplexFormatter klass som representerar ett komplext tal som en sträng i form av antingen a + bi eller 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 c1)
        {
            // Check if the format string has a precision specifier.
            int precision;
            string fmtString = string.Empty;
            if (format.Length > 1)
            {
                try
                {
                    precision = int.Parse(format.Substring(1));
                }
                catch (FormatException)
                {
                    precision = 0;
                }
                fmtString = "N" + precision.ToString();
            }
            if (format.Substring(0, 1).Equals("I", StringComparison.OrdinalIgnoreCase))
            {
                // Determine the sign to display.
                char sign = c1.Imaginary < 0 ? '-' : '+';
                // Display the determined sign and the absolute value of the imaginary part.
                return c1.Real.ToString(fmtString) + " " + sign + " " + Math.Abs(c1.Imaginary).ToString(fmtString) + "i";
            }
            else if (format.Substring(0, 1).Equals("J", StringComparison.OrdinalIgnoreCase))
            {
                // Determine the sign to display.
                char sign = c1.Imaginary < 0 ? '-' : '+';
                // Display the determined sign and the absolute value of the imaginary part.
                return c1.Real.ToString(fmtString) + " " + sign + " " + Math.Abs(c1.Imaginary).ToString(fmtString) + "j";
            }
            else
                return c1.ToString(format, provider);
        }
        else
        {
            if (arg is IFormattable formattable)
                return formattable.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 = Integer.Parse(fmt.Substring(1))
                Catch e As FormatException
                    precision = 0
                End Try
                fmtString = "N" + precision.ToString()
            End If
            ' Determine the sign to display.
            Dim sign As Char = If(c1.Imaginary < 0.0, "-"c, "+"c)
            ' Display the determined sign and the absolute value of the imaginary part.
            If fmt.Substring(0, 1).Equals("I", StringComparison.OrdinalIgnoreCase) Then
                Return c1.Real.ToString(fmtString) + " " + sign + " " + Math.Abs(c1.Imaginary).ToString(fmtString) + "i"
            ElseIf fmt.Substring(0, 1).Equals("J", StringComparison.OrdinalIgnoreCase) Then
                Return c1.Real.ToString(fmtString) + " " + sign + " " + Math.Abs(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

I följande exempel används sedan den här anpassade formateren för att visa strängrepresentationen av ett komplext tal.

public class CustomFormatEx
{
    public static void Run()
    {
        Complex c1 = new(12.1, 15.4);
        Console.WriteLine($"Formatting with ToString:         {c1}");
        Console.WriteLine($"Formatting with ToString(format): {c1:N2}");
        Console.WriteLine($"Custom formatting with I0:\t" +
            $"  {string.Format(new ComplexFormatter(), "{0:I0}", c1)}");
        Console.WriteLine($"Custom formatting with J3:\t" +
            $"  {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 Run()
        Dim c1 As New Complex(12.1, 15.4)
        Console.WriteLine($"Formatting with ToString():       {c1}")
        Console.WriteLine($"Formatting with ToString(format): {c1: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

Konstruktorer

Name Description
Complex(Double, Double)

Initierar en ny instans av Complex strukturen med de angivna verkliga och imaginära värdena.

Fält

Name Description
ImaginaryOne

Returnerar en ny Complex instans med ett verkligt tal som är lika med noll och ett imaginärt tal som är lika med en.

Infinity

Representerar oändligheten som ett komplext tal.

NaN

Representerar en komplex instans som inte är ett tal (NaN).

One

Returnerar en ny Complex instans med ett verkligt tal som är lika med en och ett imaginärt tal som är lika med noll.

Zero

Returnerar en ny Complex instans med ett verkligt tal som är lika med noll och ett imaginärt tal som är lika med noll.

Egenskaper

Name Description
Imaginary

Hämtar den imaginära komponenten för det aktuella Complex objektet.

Magnitude

Hämtar storleken (eller absolutvärdet) för ett komplext tal.

Phase

Hämtar fasen för ett komplext tal.

Real

Hämtar den verkliga komponenten i det aktuella Complex objektet.

Metoder

Name Description
Abs(Complex)

Hämtar det absoluta värdet (eller storleken) för ett komplext tal.

Acos(Complex)

Returnerar vinkeln som är bågens cosinus för det angivna komplexa talet.

Add(Complex, Complex)

Lägger till två komplexa tal och returnerar resultatet.

Add(Complex, Double)

Lägger till ett komplext tal till ett reellt tal med dubbel precision och returnerar resultatet.

Add(Double, Complex)

Lägger till ett reellt tal med dubbel precision till ett komplext tal och returnerar resultatet.

Asin(Complex)

Returnerar vinkeln som är arc sinus för det angivna komplexa talet.

Atan(Complex)

Returnerar vinkeln som är arc-tangenten för det angivna komplexa talet.

Conjugate(Complex)

Beräknar konjugering av ett komplext tal och returnerar resultatet.

Cos(Complex)

Returnerar cosininen för det angivna komplexa talet.

Cosh(Complex)

Returnerar den hyperboliska cosinin för det angivna komplexa talet.

CreateChecked<TOther>(TOther)

Skapar en instans av den aktuella typen från ett värde, vilket utlöser ett spill-undantag för värden som ligger utanför det representerarbara intervallet för den aktuella typen.

CreateSaturating<TOther>(TOther)

Skapar en instans av den aktuella typen från ett värde som mättar alla värden som ligger utanför det representerarbara intervallet för den aktuella typen.

CreateTruncating<TOther>(TOther)

Skapar en instans av den aktuella typen från ett värde och trunkerar alla värden som ligger utanför det representerarbara intervallet för den aktuella typen.

Divide(Complex, Complex)

Delar upp ett komplext tal med ett annat och returnerar resultatet.

Divide(Complex, Double)

Delar upp ett komplext tal med ett reellt tal med dubbel precision och returnerar resultatet.

Divide(Double, Complex)

Delar upp ett reellt tal med dubbel precision med ett komplext tal och returnerar resultatet.

Equals(Complex)

Returnerar ett värde som anger om den aktuella instansen och ett angivet komplext tal har samma värde.

Equals(Object)

Returnerar ett värde som anger om den aktuella instansen och ett angivet objekt har samma värde.

Exp(Complex)

Returnerar e upphöjt till den ström som anges av ett komplext tal.

FromPolarCoordinates(Double, Double)

Skapar ett komplext tal från en punkts polära koordinater.

GetHashCode()

Returnerar hash-koden för det aktuella Complex objektet.

IsComplexNumber(Complex)

Avgör om ett värde representerar ett komplext värde.

IsEvenInteger(Complex)

Avgör om ett värde representerar ett jämnt heltal.

IsFinite(Complex)

Avgör om det angivna komplexa talet är begränsat.

IsImaginaryNumber(Complex)

Avgör om ett värde representerar ett imaginärt tal.

IsInfinity(Complex)

Returnerar ett värde som anger om det angivna komplexa talet utvärderas till oändligheten.

IsInteger(Complex)

Avgör om ett värde representerar ett integralvärde.

IsNaN(Complex)

Returnerar ett värde som anger om den angivna komplexa instansen inte är ett tal (NaN).

IsNegative(Complex)

Avgör om ett värde är negativt.

IsNegativeInfinity(Complex)

Avgör om ett värde är negativ oändlighet.

IsNormal(Complex)

Avgör om ett värde är normalt.

IsOddInteger(Complex)

Avgör om ett värde representerar ett udda integraltal.

IsPositive(Complex)

Avgör om ett värde är positivt.

IsPositiveInfinity(Complex)

Avgör om ett värde är positiv oändlighet.

IsRealNumber(Complex)

Avgör om ett värde representerar ett verkligt tal.

IsSubnormal(Complex)

Avgör om ett värde är subnormalt.

Log(Complex, Double)

Returnerar logaritmen för ett angivet komplext tal i en angiven bas.

Log(Complex)

Returnerar den naturliga logaritmen (bas e) för ett angivet komplext tal.

Log10(Complex)

Returnerar logaritmen base-10 för ett angivet komplext tal.

MaxMagnitude(Complex, Complex)

Jämför två värden med beräkning som är större.

MinMagnitude(Complex, Complex)

Jämför två värden med beräkning som är mindre.

Multiply(Complex, Complex)

Returnerar produkten av två komplexa tal.

Multiply(Complex, Double)

Returnerar produkten av ett komplext tal och ett reellt tal med dubbel precision.

Multiply(Double, Complex)

Returnerar produkten av ett reellt tal med dubbel precision och ett komplext tal.

Negate(Complex)

Returnerar additiv invertering av ett angivet komplext tal.

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Representerar ett komplext tal.

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Representerar ett komplext tal.

Parse(ReadOnlySpan<Char>, IFormatProvider)

Parsar ett teckenintervall till ett värde.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Parsar ett teckenintervall till ett värde.

Parse(String, IFormatProvider)

Parsar en sträng till ett värde.

Parse(String, NumberStyles, IFormatProvider)

Parsar en sträng till ett värde.

Pow(Complex, Complex)

Returnerar ett angivet komplext tal som har upphöjts till en ström som anges av ett komplext tal.

Pow(Complex, Double)

Returnerar ett angivet komplext tal upphöjt till en effekt som anges av ett flyttal med dubbel precision.

Reciprocal(Complex)

Returnerar den multiplicativa inversen av ett komplext tal.

Sin(Complex)

Returnerar sinus för det angivna komplexa talet.

Sinh(Complex)

Returnerar hyperbolisk sinus för det angivna komplexa talet.

Sqrt(Complex)

Returnerar kvadratroten för ett angivet komplext tal.

Subtract(Complex, Complex)

Subtraherar ett komplext tal från ett annat och returnerar resultatet.

Subtract(Complex, Double)

Subtraherar ett reellt tal med dubbel precision från ett komplext tal och returnerar resultatet.

Subtract(Double, Complex)

Subtraherar ett komplext tal från ett reellt tal med dubbel precision och returnerar resultatet.

Tan(Complex)

Returnerar tangensen för det angivna komplexa talet.

Tanh(Complex)

Returnerar den hyperboliska tangensen för det angivna komplexa talet.

ToString()

Konverterar värdet för det aktuella komplexa talet till motsvarande strängrepresentation i kartesisk form.

ToString(IFormatProvider)

Konverterar värdet för det aktuella komplexa talet till motsvarande strängrepresentation i kartesisk form med hjälp av den angivna kulturspecifika formateringsinformationen.

ToString(String, IFormatProvider)

Konverterar värdet för det aktuella komplexa talet till motsvarande strängrepresentation i kartesisk form med hjälp av det angivna formatet och kulturspecifik formatinformation för dess verkliga och imaginära delar.

ToString(String)

Konverterar värdet för det aktuella komplexa talet till motsvarande strängrepresentation i kartesisk form med hjälp av det angivna formatet för dess verkliga och imaginära delar.

TryFormat(Span<Byte>, Int32, ReadOnlySpan<Char>, IFormatProvider)

Försöker formatera värdet för den aktuella instansen som UTF-8 i det angivna byteintervallet.

TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider)

Försöker formatera värdet för den aktuella instansen till det angivna intervallet med tecken.

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Complex)

Representerar ett komplext tal.

TryParse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider, Complex)

Representerar ett komplext tal.

TryParse(ReadOnlySpan<Char>, IFormatProvider, Complex)

Försöker parsa ett teckenintervall till ett värde.

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Complex)

Försöker parsa ett teckenintervall till ett värde.

TryParse(String, IFormatProvider, Complex)

Försöker parsa en sträng till ett värde.

TryParse(String, NumberStyles, IFormatProvider, Complex)

Försöker parsa en sträng till ett värde.

Operatorer

Name Description
Addition(Complex, Complex)

Lägger till två komplexa tal.

Addition(Complex, Double)

Lägger till ett komplext tal till ett reellt tal med dubbel precision.

Addition(Double, Complex)

Lägger till ett reellt tal med dubbel precision till ett komplext tal.

Decrement(Complex)

Minskar ett värde.

Division(Complex, Complex)

Delar upp ett angivet komplext tal med ett annat angivet komplext tal.

Division(Complex, Double)

Delar upp ett angivet komplext tal med ett angivet reellt tal med dubbel precision.

Division(Double, Complex)

Delar ett angivet reellt tal med dubbel precision med ett angivet komplext tal.

Equality(Complex, Complex)

Returnerar ett värde som anger om två komplexa tal är lika med.

Explicit(BigInteger to Complex)

Definierar en explicit konvertering av ett BigInteger värde till ett komplext tal.

Explicit(Decimal to Complex)

Definierar en explicit konvertering av ett Decimal värde till ett komplext tal.

Explicit(Int128 to Complex)

Konverterar uttryckligen ett Int128 värde till ett komplext tal med dubbel precision.

Explicit(UInt128 to Complex)

Konverterar uttryckligen ett UInt128 värde till ett komplext tal med dubbel precision.

Implicit(BFloat16 to Complex)

Representerar ett komplext tal.

Implicit(Byte to Complex)

Definierar en implicit konvertering av en osignerad byte till ett komplext tal.

Implicit(Char to Complex)

Konverterar implicit ett Char värde till ett komplext tal med dubbel precision.

Implicit(Double to Complex)

Definierar en implicit konvertering av ett flyttal med dubbel precision till ett komplext tal.

Implicit(Half to Complex)

Konverterar implicit ett Half värde till ett komplext tal med dubbel precision.

Implicit(Int16 to Complex)

Definierar en implicit konvertering av ett 16-bitars signerat heltal till ett komplext tal.

Implicit(Int32 to Complex)

Definierar en implicit konvertering av ett 32-bitars signerat heltal till ett komplext tal.

Implicit(Int64 to Complex)

Definierar en implicit konvertering av ett 64-bitars signerat heltal till ett komplext tal.

Implicit(IntPtr to Complex)

Konverterar implicit ett IntPtr värde till ett komplext tal med dubbel precision.

Implicit(SByte to Complex)

Definierar en implicit konvertering av en signerad byte till ett komplext tal.

Detta API uppfyller inte CLS.

Implicit(Single to Complex)

Definierar en implicit konvertering av ett flyttal med enkel precision till ett komplext tal.

Implicit(UInt16 to Complex)

Definierar en implicit konvertering av ett 16-bitars osignerat heltal till ett komplext tal.

Detta API uppfyller inte CLS.

Implicit(UInt32 to Complex)

Definierar en implicit konvertering av ett 32-bitars osignerat heltal till ett komplext tal.

Detta API uppfyller inte CLS.

Implicit(UInt64 to Complex)

Definierar en implicit konvertering av ett 64-bitars osignerat heltal till ett komplext tal.

Detta API uppfyller inte CLS.

Implicit(UIntPtr to Complex)

Konverterar implicit ett UIntPtr värde till ett komplext tal med dubbel precision.

Increment(Complex)

Ökar ett värde.

Inequality(Complex, Complex)

Returnerar ett värde som anger om två komplexa tal inte är lika med.

Multiply(Complex, Complex)

Multiplicerar två angivna komplexa tal.

Multiply(Complex, Double)

Multiplicerar det angivna komplexa talet med ett angivet reellt tal med dubbel precision.

Multiply(Double, Complex)

Multiplicerar ett angivet reellt tal med dubbel precision med ett angivet komplext tal.

Subtraction(Complex, Complex)

Subtraherar ett komplext tal från ett annat komplext tal.

Subtraction(Complex, Double)

Subtraherar ett reellt tal med dubbel precision från ett komplext tal.

Subtraction(Double, Complex)

Subtraherar ett komplext tal från ett reellt tal med dubbel precision.

UnaryNegation(Complex)

Returnerar additiv invertering av ett angivet komplext tal.

UnaryPlus(Complex)

Beräknar det unary plus av ett värde.

Explicita gränssnittsimplementeringar

Name Description
IAdditiveIdentity<Complex,Complex>.AdditiveIdentity

Hämtar den aktuella typens additiva identitet.

IMultiplicativeIdentity<Complex,Complex>.MultiplicativeIdentity

Hämtar den multiplicativa identiteten för den aktuella typen.

INumberBase<Complex>.Abs(Complex)

Beräknar det absoluta värdet.

INumberBase<Complex>.IsCanonical(Complex)

Avgör om ett värde finns i dess kanoniska representation.

INumberBase<Complex>.IsZero(Complex)

Avgör om ett värde är noll.

INumberBase<Complex>.MaxMagnitudeNumber(Complex, Complex)

Jämför två värden med beräkning som har större storlek och returnerar det andra värdet om en indata är NaN.

INumberBase<Complex>.MinMagnitudeNumber(Complex, Complex)

Jämför två värden med beräkning som har mindre storlek och returnerar det andra värdet om en indata är NaN.

INumberBase<Complex>.MultiplyAddEstimate(Complex, Complex, Complex)

Beräknar en uppskattning av (left * right) + addend.

INumberBase<Complex>.One

Hämtar värdet 1 för typen.

INumberBase<Complex>.Radix

Hämtar radixet, eller basen, för typen.

INumberBase<Complex>.TryConvertFromChecked<TOther>(TOther, Complex)

Representerar ett komplext tal.

INumberBase<Complex>.TryConvertFromSaturating<TOther>(TOther, Complex)

Representerar ett komplext tal.

INumberBase<Complex>.TryConvertFromTruncating<TOther>(TOther, Complex)

Representerar ett komplext tal.

INumberBase<Complex>.TryConvertToChecked<TOther>(Complex, TOther)

Försöker konvertera en instans av den aktuella typen till en annan typ, vilket utlöser ett spill-undantag för värden som ligger utanför det representerarbara intervallet för den aktuella typen.

INumberBase<Complex>.TryConvertToSaturating<TOther>(Complex, TOther)

Försöker konvertera en instans av den aktuella typen till en annan typ, vilket mättar alla värden som ligger utanför det representerarbara intervallet för den aktuella typen.

INumberBase<Complex>.TryConvertToTruncating<TOther>(Complex, TOther)

Försöker konvertera en instans av den aktuella typen till en annan typ och trunkerar alla värden som ligger utanför det representerarbara intervallet för den aktuella typen.

INumberBase<Complex>.Zero

Hämtar värdet 0 för typen.

ISignedNumber<Complex>.NegativeOne

Hämtar värdet -1 för typen.

Gäller för