Skip to content

Instantly share code, notes, and snippets.

@andrevidela
Last active January 7, 2019 14:40
Show Gist options
  • Save andrevidela/52643d9b12761b18d55bdab479292cf7 to your computer and use it in GitHub Desktop.
Save andrevidela/52643d9b12761b18d55bdab479292cf7 to your computer and use it in GitHub Desktop.
struct Complex: Equatable {
let real: Double
let imm: Double
}
extension Complex: CustomStringConvertible {
var description: String { return "\(real) + \(imm)i" }
}
extension Complex: TwoDimensions {
typealias ComponentVal = Double
static func make2D(_ fst: Double, _ snd: Double) -> Complex {
return Complex(real: fst, imm: snd)
}
var fst: Double { return real }
var snd: Double { return imm }
}
extension Complex: Additive {}
extension Complex: Scalar { typealias ScalarVal = Double }
extension Complex: Magnitude {}
// Complex numbers have a multiplication such that
// (a + bi) * (c + di) = a * c + (a * d)i + (b * c)i + (b * d)i²
// since i² = -1 we have
// (a + bi) * (c + di) = a * c - b * d + (a * d + b * c)
extension Complex: Multiplicative {
static var multId: Complex {
return Complex(real: 1.0 , imm: 0.0)
}
static func * (_ lhs: Complex, _ rhs: Complex) -> Complex {
return Complex(real: lhs.real * rhs.real - lhs.imm * rhs.imm,
imm: lhs.real * rhs.imm + lhs.imm * rhs.real)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment