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.

timbo
  • 13,244
  • 8
  • 51
  • 71
yairchu
  • 23,680
  • 7
  • 69
  • 109

3 Answers3

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

dankogai
  • 1,627
  • 12
  • 7
  • 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. – kawingkelvin Sep 18 '14 at 03:28
2

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

Cezar
  • 55,636
  • 19
  • 86
  • 87
  • 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. – kawingkelvin Sep 18 '14 at 15:53
  • typo: "integer extension" is "Double extension" – kawingkelvin Sep 18 '14 at 16:05
2

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)
rob mayoff
  • 375,296
  • 67
  • 796
  • 848