Last active
January 7, 2019 14:40
-
-
Save andrevidela/52643d9b12761b18d55bdab479292cf7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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