RosettaCodeData/Task/Arithmetic-Complex/FreeBASIC/arithmetic-complex.freebasic

66 lines
1.5 KiB
Plaintext

' FB 1.05.0 Win64
Type Complex
As Double real, imag
Declare Constructor(real As Double, imag As Double)
Declare Function invert() As Complex
Declare Function conjugate() As Complex
Declare Operator cast() As String
End Type
Constructor Complex(real As Double, imag As Double)
This.real = real
This.imag = imag
End Constructor
Function Complex.invert() As Complex
Dim denom As Double = real * real + imag * imag
Return Complex(real / denom, -imag / denom)
End Function
Function Complex.conjugate() As Complex
Return Complex(real, -imag)
End Function
Operator Complex.Cast() As String
If imag >= 0 Then
Return Str(real) + "+" + Str(imag) + "j"
End If
Return Str(real) + Str(imag) + "j"
End Operator
Operator - (c As Complex) As Complex
Return Complex(-c.real, -c.imag)
End Operator
Operator + (c1 As Complex, c2 As Complex) As Complex
Return Complex(c1.real + c2.real, c1.imag + c2.imag)
End Operator
Operator - (c1 As Complex, c2 As Complex) As Complex
Return c1 + (-c2)
End Operator
Operator * (c1 As Complex, c2 As Complex) As Complex
Return Complex(c1.real * c2.real - c1.imag * c2.imag, c1.real * c2.imag + c2.real * c1.imag)
End Operator
Operator / (c1 As Complex, c2 As Complex) As Complex
Return c1 * c2.invert
End Operator
Var x = Complex(1, 3)
Var y = Complex(5, 2)
Print "x = "; x
Print "y = "; y
Print "x + y = "; x + y
Print "x - y = "; x - y
Print "x * y = "; x * y
Print "x / y = "; x / y
Print "-x = "; -x
Print "1 / x = "; x.invert
Print "x* = "; x.conjugate
Print
Print "Press any key to quit"
Sleep