Skip to content

Instantly share code, notes, and snippets.

@dduan
Forked from mattt/Complex.swift
Last active August 29, 2015 14:12
Show Gist options
  • Save dduan/b931c8f3f5443e0bb43c to your computer and use it in GitHub Desktop.
Save dduan/b931c8f3f5443e0bb43c to your computer and use it in GitHub Desktop.
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