Private m_RealPart As Single
Private m_ImaginaryPart As Single
Public Property Get RealPart() As Single
RealPart = m_RealPart
End Property
Public Property Let RealPart(ByVal real_part As Single)
m_RealPart = real_part
End Property
Public Property Get ImaginaryPart() As Single
ImaginaryPart = m_ImaginaryPart
End Property
Public Property Let ImaginaryPart(ByVal imaginary_part As _
Single)
m_ImaginaryPart = imaginary_part
End Property
' Set the real and imaginary parts.
Public Sub SetParts(Optional ByVal real_part As Single = _
0#, Optional ByVal imaginary_part As Single = 0#)
m_RealPart = real_part
m_ImaginaryPart = imaginary_part
End Sub
' Initialize the ComplexNumber from a string.
Public Sub FromString(ByVal txt As String)
Dim pos As Integer
Dim parts() As String
' Remove spaces and the "i".
txt = Replace$(txt, " ", "")
txt = Replace$(LCase$(txt), "i", "")
' Find the + or - between the parts.
pos = InStr(Replace$(txt, "-", "+"), "+")
If pos = 1 Then
' Skip the leading +/-.
pos = InStr(2, Replace$(txt, "-", "+"), "+")
End If
' Get the real and imaginary parts.
m_RealPart = CSng(Mid$(txt, 1, pos - 1))
m_ImaginaryPart = CSng(Mid$(txt, pos))
End Sub
' Return -Me.
Public Function Negate() As ComplexNumber
Dim result As New ComplexNumber
result.SetParts -m_RealPart, -m_ImaginaryPart
Set Negate = result
End Function
' Return Me + complex_number.
Public Function Plus(ByVal complex_number As ComplexNumber) _
As ComplexNumber
Dim result As New ComplexNumber
result.SetParts _
m_RealPart + complex_number.RealPart, _
m_ImaginaryPart + complex_number.ImaginaryPart
Set Plus = result
End Function
' Return Me - complex_number.
Public Function Minus(ByVal complex_number As _
ComplexNumber) As ComplexNumber
Set Minus = Me.Plus(complex_number.Negate())
End Function
' Return Me * complex_number.
Public Function Times(ByVal complex_number As _
ComplexNumber) As ComplexNumber
Dim result As New ComplexNumber
Dim re_part As Single
Dim im_part As Single
re_part = _
m_RealPart * complex_number.RealPart - _
m_ImaginaryPart * complex_number.ImaginaryPart
im_part = _
m_RealPart * complex_number.ImaginaryPart + _
m_ImaginaryPart * complex_number.RealPart
result.SetParts re_part, im_part
Set Times = result
End Function
' Return a string representation of this number.
Public Function ToString() As String
Dim result As String
' Start with the real part.
result = Format$(m_RealPart)
' Add the imaginary part.
If m_ImaginaryPart >= 0 Then
result = result & " + " & _
Format$(m_ImaginaryPart) & "i"
Else
result = result & " - " & _
Format$(Abs(m_ImaginaryPart)) & "i"
End If
ToString = result
End Function
|