Skip to content

Instantly share code, notes, and snippets.

@dduan

dduan/Complex.swift

Forked from mattt/Complex.swift
Last active Aug 29, 2015
Embed
What would you like to do?
struct Complex<T: FloatLiteralConvertible> {
var real: T
var imaginary: T
}
func +(lhs: Complex<Double>, rhs: Complex<Double>) -> Complex<Double> {
return Complex<Double>(real: lhs.real + rhs.real, imaginary: lhs.imaginary + rhs.imaginary)
}
func -(lhs: Complex<Double>, rhs: Complex<Double>) -> Complex<Double> {
return Complex<Double>(real: lhs.real - rhs.real, imaginary: lhs.imaginary - rhs.imaginary)
}
func *(lhs: Complex<Double>, rhs: Complex<Double>) -> Complex<Double> {
return Complex<Double>(
real: lhs.real * rhs.real - lhs.imaginary * rhs.imaginary,
imaginary: lhs.imaginary * rhs.real + lhs.real * rhs.imaginary
)
}
func /(lhs: Complex<Double>, rhs: Complex<Double>) -> Complex<Double> {
let temp = rhs.real * rhs.real + rhs.imaginary * rhs.imaginary
return Complex<Double>(
real: (lhs.real * rhs.real + lhs.imaginary * rhs.imaginary) / temp,
imaginary: (lhs.imaginary * rhs.real - lhs.real * rhs.imaginary) / temp
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment