Thursday, June 7, 2018

Complex numbers - simple calculations

This example is tested with Xcode 9.2 playground in Swift 4.0.3. Basic complex number calculations such as the magnitude are includes as below:


class ComplexNum {
    var real : Float
    var imag : Float
    
    init (real: Float, imag: Float){
        self.real = real
        self.imag = imag
    }
    func show()->String {
        let plusChar = (imag>0) ? "+" : "-"
        return "\(real) \(plusChar) \(abs(imag))i"
    }
    //Magnitude
    func mag()->Float {
        return sqrt(self.real*self.real+self.imag*self.imag)
    }
    //Quick calculation with (i)
    func multiplyPlusI(num:ComplexNum) -> ComplexNum{
        return ComplexNum(real: -num.imag, imag: num.real)
    }
    //Quick calculation with (-i)
    func multiplyMinusI(num:ComplexNum) -> ComplexNum{
        return ComplexNum(real: num.imag, imag: -num.real)
    }
}
func addComplex(a: ComplexNum, b: ComplexNum)->ComplexNum {
    return ComplexNum(real: a.real+b.real, imag: a.imag+b.imag)
}
func multiplyComplex(a: ComplexNum, b: ComplexNum)->ComplexNum {
    return ComplexNum(real: a.real*b.real-a.imag*b.imag, imag: a.real*b.imag+a.imag*b.real)
}

let x = ComplexNum(real: 3, imag: 1)
print("x = \(x.show())")
print("|x| = \(x.mag())")
print("x(j) = \(x.multiplyPlusI(num: x).show())")
print("x(-j) = \(x.multiplyMinusI(num: x).show())")

let y = ComplexNum(real: -1, imag: -2)
print("y = \(y.show())")
print("|y| = \(y.mag())")
print("y(j) = \(x.multiplyPlusI(num: y).show())")
print("y(-j) = \(x.multiplyMinusI(num: y).show())")

print("x + y = \(addComplex(a: x, b: y).show())")
print("x * y = \(multiplyComplex(a: x, b: y).show())")

Results:


x = 3.0 + 1.0i
|x| = 3.16228
x(j) = -1.0 + 3.0i
x(-j) = 1.0 - 3.0i
y = -1.0 - 2.0i
|y| = 2.23607
y(j) = 2.0 - 1.0i
y(-j) = -2.0 + 1.0i
x + y = 2.0 - 1.0i
x * y = -1.0 - 7.0i

Related Information:
Matlab: Real and imaginary parts of complex number and multiplication with imaginary unit j