Swift Numerics

Steve Canon is a member of Apple’s Swift Standard Library team. Previously he spent a decade working on Apple’s math library and the Accelerate framework.

I’m excited to announce a new open-source project for the Swift ecosystem, Swift Numerics! Swift Numerics will provide the building blocks of numerical computing in Swift, as a set of fine-grained modules bundled together into a single Swift package. My hope is that we can quickly fill some important gaps in the Standard Library’s existing APIs, and unlock new domains of programming to the Swift language.

I’ve seeded the repository with two much-requested modules that are immediately useful for computational mathematics: Real (providing the functionality of SE-0246) and Complex (providing complex numbers and arithmetic). Let’s take a look at what they do:

Real Numbers

SE-0246 proposed an API for “basic math functions” that would make operations like sine and logarithm available in generic contexts. It was accepted, but because of limitations in the compiler, the API cannot yet be added to the Standard Library in a source-stable manner. The Real module provides that API as a separate module so that you can use it right away to get access to the improved API for these operations in your projects.

The module defines three protocols. The most general is ElementaryFunctions, which makes the following functions available:

The RealFunctions protocol refines ElementaryFunctions, and adds operations that are difficult to define or implement over fields more general than the real numbers:

The protocol that you will use most often is Real, which describes a floating-point type equipped with the full set of basic math functions. This is a great protocol to use in writing generic code, because it has all the basics that you need to implement most numeric functions. Suppose we were experimenting with some basic machine learning, and needed a generic sigmoid function activation function:

import Numerics

func sigmoid<T: Real>(_ x: T) -> T {
  1 / (1 + .exp(-x))
}

Or suppose we were implementing a DFT, and wanted to precompute weights for the transform; DFT weights are roots of unity:

import Numerics

extension Real {
  // The real and imaginary parts of e^{-2πik/n}
  static func dftWeight(k: Int, n: Int) -> (r: Self, i: Self) {
    precondition(0 <= k && k < n, "k is out of range")
    guard let N = Self(exactly: n) else {
      preconditionFailure("n cannot be represented exactly.")
    }
    let theta = -2 * .pi * (Self(k) / N)
    return (r: .cos(theta), i: .sin(theta))
  }
}

This gives us an implementation that works for Float, Double, and Float80 if the target supports it. When new basic floating-point types are added to Swift, like Float16 or Float128, it will work for them as well. This module–especially the Real protocol–is a significant improvement to generic numerical computing in Swift, and I’m really looking forward to seeing what you do with it.

Complex Numbers

The Complex module builds on Real to provide a complex number type for Swift.

Complex numbers are useful for computation because they are the “smallest algebraically-closed field that contains the rational numbers”. What that means in practice is that common equations (like those that give the roots of a polynomial or the eigenvalues of a matrix) do not necessarily have solutions in the real numbers, but are guaranteed to have solutions in the complex numbers. This seems like an esoteric fact, but when you develop algorithms, a guarantee that solutions exist is often useful.

Complex numbers arise naturally in computation when working with Fourier transforms: the Fourier transform of a real signal is a symmetric complex signal. This means that the natural setting for many signal processing algorithms used in everything from audio processing to circuit simulations is the complex numbers. Libraries frequently hide this detail from you in routine use, but when developing libraries, it’s critical to have this tool available.

For example, the dftWeight code that we showed above can be written more naturally using Complex as:

import Numerics

extension Complex {
  // e^{-2πik/n}
  static func dftWeight(k: Int, n: Int) -> Complex {
    precondition(0 <= k && k < n, "k is out of range")
    guard let N = RealType(exactly: n) else {
      preconditionFailure("n cannot be represented exactly.")
    }
    return Complex(length: 1, phase: -2 * .pi * (RealType(k) / N))!
  }
}

For these reasons complex numbers are an important building block that most languages or standard libraries provide. C has _Complex, C++ has std::complex, Fortran and Python have complex numbers built right into the language core. I expect that once the Swift Numerics module has some use and we do a few iterations of building out its features, we’ll propose part of it for inclusion in the Swift Standard Library as well.

The Complex type is generic over an underlying RealType, which conforms to Real.

public struct Complex<RealType> where RealType: Real {
  ...
}

Why not support Complex<T> for integer types T as well? While the Gaussian integers are “just like” the complex numbers–they’re a subset, after all–the actual operations that you perform on them (and the ideal implementation of those operations) are quite different, so it doesn’t make sense to force them together into a single generic type. I would love to see support for Gaussian integers added to the library at some future point, but it should be a separate type from Complex.

As a refresher, complex numbers have two components, a real part and an imaginary part. There’s a special number, called i, which is the imaginary unit. In mathematics, we write a complex number with real part a and imaginary part b as a + bi. In Swift, it looks pretty similar:

import Complex

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

Swift Numerics prints complex numbers in Fortran style; a + bi is (a, b):

print(z) // (2.0, 3.0)

You can also construct a complex number by specifying its real and imaginary parts:

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

to add two complex numbers, we add the corresponding parts:

print(z + w) // (2.0 + 1.0, 3.0 + -2.0) = (3.0, 1.0)

Multiplication and division are only a little bit more complicated; their definitions follow from the identity:

let u: Complex<Double> = .i * .i // (-1.0, 0.0)

(i.e. i is a square root of -1). The Complex type conforms to the Numeric protocol, and uses the usual division operator /, so arithmetic on complex numbers looks just like it does on any other number type. For example, here’s a function that implements multiplication by 2i, which is a 2x scaling and 90˚ rotation in the complex plane:

import Complex

func scaleAndRotate<T>(_ z: Complex<T>) -> Complex<T> {
  z * Complex(0, 2)
}

let z = scaleAndRotate(Complex(1.0, 1.0)) // (-2.0, 2.0)

At this point, it’s worth talking a little about infinities and NaNs and their implications for multiplication and division. The C and C++ complex math libraries attempt to make fine-grained distinctions between different zeros and infinities and NaNs. This is occasionally useful, but it means that multiplication cannot use the obvious arithmetic expression.

Swift does not attempt to make this distinction. Any complex number with zero real and imaginary parts is zero, and all complex numbers with a non-finite real or imaginary part are collapsed into a single “point at infinity”.

[ 1> import Complex
[ 2> Complex(.infinity, 0.0) == Complex(0.0, -.nan)
$R0: Bool = true

This loses a little bit of information, but very few programs make productive use of the distinction, and all programs have their performance adversely effected by the decision to try to keep it around. To make the performance impact concrete, let’s compare the throughput of double-precision complex multiplication on my 2015 MacBook Pro:

Data distribution C Swift Speedup
well-scaled 1 / 1.4ns 1 / 1.1ns 1.3x
poorly-scaled 1 / 4.5ns 1 / 4.1ns 1.1x

A note on benchmarking measurements and methodology: throughput in these tables is reported in units of reciprocal time. 1/1.1ns means “one result is produced every 1.1 nanoseconds”. Smaller denominators are better than larger denominators; 1/1.5ns is twice as fast as 1/3ns. These benchmarks do not perform multiplication (or division) in isolation; instead they are measuring the time to compute and sum a set of multiplication (or division) results. This introduces some overhead to the measurement, but that overhead falls disproportionately on the faster operation, so this makes the Swift performance look worse than it really is. You can see the (very simple) benchmark code in ArithmeticBenchmarkTests.swift. Pull requests to add more sophisticated benchmarking are welcome!

Because Swift Numerics doesn’t need to give special attention to infinities, it is about 30% faster in the common case where values are well-scaled, and somewhat faster even in the unusual case where there are many poorly-scaled values. In pathological cases where there are a large number of infinities or NaNs in the data set, the difference will be greater.

There’s an even larger impact for division:

Data distribution C Swift Speedup
well-scaled 1 / 19 ns 1 / 5ns 3.8x
poorly-scaled 1 / 22 ns 1 / 22ns n/a

Because Swift Numerics’ complex division operation is exposed to the compiler, it allows greater opportunity for optimization when dividing many values by a single divisor (a very common operation). Here’s the same table, if we divide a whole array of values by a single common well-scaled divisor:

Data distribution C Swift Speedup
well-scaled 1 / 19 ns 1 / 1.8ns 10.6x

I have one last trick up my sleeve: if the data is well-scaled, we can use the reciprocal property and multiply instead, which brings performance up to 1/1.1ns–a 17x speedup! This is possible in C as well, of course, but Swift’s optional semantics gives an easy mechanism that makes it safe:

// If divisor is well-scaled, use multiply by reciprocal instead of division.
if let recip = divisor.reciprocal {
  return data.map { $0 * recip }
}
// Otherwise, fallback on using division.
return data.map { $0 / divisor }

Swift Numerics also gives better answers for complex divisions in some especially difficult cases–consider the following test problem, from Baudin & Smith’s paper “A Robust Complex Division in Scilab”:

Complex(0x1p-1074, 0x1p-1074) / Complex(0x1p-1073, 0x1p-1074)

This looks simple enough; if we scale both the numerator and denominator by 0x1p1074, the problem becomes (1 + i)/(2 + i), and we can compute the result by hand:

(1+i)/(2+i) = (1+i)(2-i)/5 = ((2+1) + (2-1)i)/5 = (3+i)/5 = (0.6, 0.2)

Clang (using compiler-rt) produces (0.5, 0.5) in both C and C++ for this division. Python’s complex numbers give a result of (1.0, 0.0). The Complex module gives an answer as accurate as you deserve: (0.6, 0.2), and does it without sacrificing any performance.

I’m currently working on a patch to make Complex conform to ElementaryFunctions, which makes the usual set of transcendental operations available, and brings Complex up to feature parity with most other languages. Expect this to be available in the next couple weeks.

Why a Package?

Why am I doing this work as a package, rather than in the Standard Library? There are a few reasons, but the major one is simply that not everything should go into the Standard Library. Some pieces of Swift Numerics will probably make their way into the Standard Library over time, but some modules need to have a home that isn’t part of every project by default. My goal for Swift Numerics is that it provides a common home for such modules that are centered on numerical computing, just like SwiftNIO does for networking.

Making a package has a few other nice benefits:

Future Plans

In the next few months, I’ll be working to add important additional functionality to the package. In particular, a few of the focus areas will be:

All of these projects (and others) are tracked on the issues page for Swift Numerics.

Get Involved!

I love working on Swift Numerics, but I want you to get involved, too.

Questions?

Please feel free to post questions about this post on the associated thread on the Swift forums.