Complex numbers in Swift.
Swift 2.0 or better. For Swift 1.x and below see the swift-1.x branch (which is no longer maintained).
Just add complex/complex.swift to it.
git clone https://github.com/dankogai/swift-complex.git
cd swift-complex/complex
xcrun -sdk macosx swiftc *.swift && ./main
let z0 = 1 + 1.i
let z1 = 1 - 1.i
println(z0 * z1) // (2.0+0.0.i)
println(z0 * z1 == z0 + z1) // true
println(z0 * z1 == 2) // true
complex.swift implements all the functionality of std::complex in c++11, arguably more intuitively.
- Instead of defining the constant
i
,Double
andComplex
have a property.i
which returnsself * Complex(0,1)
so it does not pollute the identifieri
, too popularly used for iteration to make it a constant. - Following functions are also provided as properties:
z.real
forreal(z)
z.imag
forimag(z)
z.abs
forabs(z)
z.arg
forarg(z)
z.norm
fornorm(z)
z.conj
forconj(z)
z.proj
forproj(z)
- Construct a complex number via polar notation as:
Complex(abs:magnitude, arg:argument)
- In addition to
pow()
, it comes with the**
operator - Generic! (as of version 0.3.0)
- Complex numbers are
Complex<T>
whereT
is a type of.re
and.im
that conforms to theRealType
protocol. See the source to find whatRealType
is doing.
- Complex numbers are