Complex Number : Complex Number « Data Type « VB.Net Tutorial






Public Class Tester


    Public Shared Sub Main
        Dim result As New System.Text.StringBuilder
        Dim a As ComplexNumber
        Dim b As ComplexNumber
        Dim c As ComplexNumber

        a = New ComplexNumber(3, 4)
        b = New ComplexNumber(5, -2)
        c = a + b

        result.AppendLine("Complex Numbers")
        result.AppendLine("a = " & a.ToString())
        result.AppendLine("b = " & b.ToString())

        ' ----- Addition.
        c = a + b
        result.AppendLine("a + b = " & c.ToString())

        ' ----- Subtraction.
        c = a - b
        result.AppendLine("a - b = " & c.ToString())

        ' ----- Multiplication.
        c = a * b
        result.AppendLine("a * b = " & c.ToString())

        ' ----- Division.
        c = a / b
        result.AppendLine("a / b = " & c.ToString())

        ' ----- Addition as assignment.
        a += b
        result.AppendLine("a += b ... a = " & a.ToString())

        Console.WriteLine(result.ToString())

    End Sub

    
End Class

Structure ComplexNumber
    Public Real As Double
    Public Imaginary As Double

    Public Sub New(ByVal realPart As Double, ByVal imaginaryPart As Double)
        Me.Real = realPart
        Me.Imaginary = imaginaryPart
    End Sub

    Public Sub New(ByVal sourceNumber As ComplexNumber)
        Me.Real = sourceNumber.Real
        Me.Imaginary = sourceNumber.Imaginary
    End Sub

    Public Overrides Function ToString() As String
        Return Real & "+" & Imaginary & "i"
    End Function

    Public Shared Operator +(ByVal a As ComplexNumber, _
            ByVal b As ComplexNumber) As ComplexNumber
        Return New ComplexNumber(a.Real + b.Real, a.Imaginary + b.Imaginary)
    End Operator

    Public Shared Operator -(ByVal a As ComplexNumber, _
            ByVal b As ComplexNumber) As ComplexNumber
        Return New ComplexNumber(a.Real - b.Real, a.Imaginary - b.Imaginary)
    End Operator

    Public Shared Operator *(ByVal a As ComplexNumber, _
            ByVal b As ComplexNumber) As ComplexNumber
        Return New ComplexNumber(a.Real * b.Real - a.Imaginary * b.Imaginary, _
            a.Real * b.Imaginary + a.Imaginary * b.Real)
    End Operator

    Public Shared Operator /(ByVal a As ComplexNumber, _
            ByVal b As ComplexNumber) As ComplexNumber
        Return a * Reciprocal(b)
    End Operator

    Public Shared Function Reciprocal(ByVal a As ComplexNumber) As ComplexNumber
        Dim divisor As Double

        divisor = a.Real * a.Real + a.Imaginary * a.Imaginary
        If (divisor = 0.0#) Then Throw New DivideByZeroException

        Return New ComplexNumber(a.Real / divisor, -a.Imaginary / divisor)
    End Function
End Structure
Complex Numbers
a = 3+4i
b = 5+-2i
a + b = 8+2i
a - b = -2+6i
a * b = 23+14i
a / b = 0.241379310344828+0.896551724137931i
a += b ... a = 8+2i








2.19.Complex Number
2.19.1.Complex
2.19.2.Complex Number