Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex numbers in Swift?

Does Apple's Swift language support complex numbers out of the box?

I couldn't find any mention in the docs any equivalent for C++ std::complex nor could I find one when playing with it.

like image 632
yairchu Avatar asked Jun 03 '14 00:06

yairchu


3 Answers

I wrote the following:

https://github.com/dankogai/swift-complex

Just add complex.swift to your project and you can go like:

let z = 1-1.i

It has all functions and operators that of C++11 covers.

Unlike C++11 complex.swift is not generic -- z.real and z.imag are always Double.

But the necessity for complex integer is very moot and IMHO it should be treated in different type (GaussianInteger, maybe).

like image 80
dankogai Avatar answered Nov 16 '22 04:11

dankogai


No. You may import the Accelerate module via import Accelerate and use the DSPComplex type. Refer to the documentation for more detail.

like image 29
Cezar Avatar answered Nov 16 '22 02:11

Cezar


Apple's Swift Numerics package supports complex numbers. It was first released on November 7, 2019. The package became stable with a 1.0.0 release on August 31, 2021.

Here are some examples from the initial release announcement :

import Complex

let z: Complex<Double> = 2 + 3 * .i
print(z.real)      // 2.0
print(z.imaginary) // 3.0

let w = Complex<Double>(1, -2) // (1.0, -2.0)

let u: Complex<Double> = .i * .i // (-1.0, 0.0)
like image 24
rob mayoff Avatar answered Nov 16 '22 03:11

rob mayoff