Complex numbers in Swift?
Asked Answered
M

3

7

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.

Misguided answered 3/6, 2014 at 0:3 Comment(1)
can you bridge in complex.h?Winfredwinfrey
G
17

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).

Granulite answered 14/6, 2014 at 10:55 Comment(1)
Yes, very elegant syntax. I like the "1.i". However, for most realistic application, they may be used in a more computational intensive context. So performance may be a great concern.Huddersfield
L
4

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)
Landlocked answered 21/11, 2021 at 20:40 Comment(0)
O
2

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

Organ answered 3/6, 2014 at 13:14 Comment(2)
My experience with Accelerate is limited to a few line of testing and watching WWDC video. I took a dive to try to convert and i to a -i as a warm up and I find thats quite lot of boilerplate code working with this in Swift, such as code that convert/bridge from one "type" to another, in order to make it interoperate with C. Most of the APIs really work with vector. So if you don't have a vectorized problem at hand, I wonder if the overhead will be worth the trouble and dankogai's neat struct and integer extension could even be more performant.Huddersfield
typo: "integer extension" is "Double extension"Huddersfield

© 2022 - 2025 — McMap. All rights reserved.