# Visualizing the Riemann Zeta Function in Swift with swift-numerics and SwiftUI

The Riemann zeta function, **ζ(s)**, is one of the most famous functions in mathematics — connecting prime numbers, complex analysis, and the million-dollar Riemann Hypothesis.

In this post, I'll walk through how I built **Riemann Zeta Explorer**, a native macOS SwiftUI app and Swift library that evaluates ζ(s) across the entire complex plane using Apple's [`swift-numerics`](https://github.com/apple/swift-numerics) package (`ComplexModule` & `RealModule`) and renders four interactive visualizations.

All source code is open source on GitHub: [erkekin/riemann-zeta-swift](https://github.com/erkekin/riemann-zeta-swift)

---

## Why Naive Summation Isn't Enough

For complex numbers `s` with `Re(s) > 1`, the Riemann zeta function is defined by the Dirichlet series:

```
ζ(s) = 1 + 1/2^s + 1/3^s + 1/4^s + ...
```

The catch is that this series **diverges** for `Re(s) ≤ 1` — which includes the entire **critical strip** `0 ≤ Re(s) ≤ 1` where all the nontrivial zeros live, as well as the negative real axis (`ζ(0) = -1/2`, `ζ(-1) = -1/12`, and trivial zeros at `-2, -4, -6, ...`).

To evaluate ζ(s) everywhere in `ℂ \ {1}`, we need **analytic continuation**.

---

## Implementing ζ(s) with `Complex<Double>`

First, add `swift-numerics` to `Package.swift`:

```swift
dependencies: [
    .package(url: "https://github.com/apple/swift-numerics", from: "1.0.2")
]
```

And link both `ComplexModule` and `RealModule` to your target (in Swift 6 strict module visibility, `RealModule` is required alongside `ComplexModule` for `Double`'s conformance to `Real`).

Our implementation in `RiemannZeta.swift` splits the complex plane into two regions:

### 1. Euler–Maclaurin Summation (`Re(s) ≥ -0.5`)

Using the Euler–Maclaurin formula with Bernoulli correction terms up to `B_20`, we sum the first `N - 1` terms directly and approximate the tail analytically:

```swift
let n = max(14, Int(ceil(abs(t))) + 14)

var sum = Complex<Double>.zero
for k in 1..<n {
    let logK = log(Double(k))
    let mag = exp(-sigma * logK)
    let angle = -t * logK
    sum += Complex(mag * cos(angle), mag * sin(angle))
}

let nDouble = Double(n)
let logN = log(nDouble)
let nPowNegS = Complex(
    exp(-sigma * logN) * cos(-t * logN),
    exp(-sigma * logN) * sin(-t * logN)
)

// Integral + trapezoidal boundary terms
sum += (Complex(nDouble, 0.0) * nPowNegS) / (s - Complex(1.0, 0.0))
sum += Complex(0.5, 0.0) * nPowNegS
```

Adding the Bernoulli correction series converges to near full `Double` precision across the entire critical strip and avoids any removable `0 · ∞` singularity at `s = 0`.

### 2. Riemann's Functional Equation (`Re(s) < -0.5`)

For the left half-plane, we reflect `s` to `1 - s` (where `Re(1 - s) > 1.5`) using Riemann's functional equation:

```
ζ(s) = 2^s · π^(s - 1) · sin(πs / 2) · Γ(1 - s) · ζ(1 - s)
```

One subtle numerical detail: for large imaginary parts `t`, `sin(πs / 2)` grows like `e^(πt/2)` while `Γ(1 - s)` decays like `e^(-πt/2)`. Computing them separately would overflow `Double`. Instead, we factor out `e^(πt/2)` from `sin(πs / 2)` and combine it in log-space with a 9-term Lanczos approximation for `log Γ(1 - s)`:

```swift
let x = 0.5 * Double.pi * s.real
let y = 0.5 * Double.pi * s.imaginary

let expNeg2y = exp(-2.0 * y)
let ePosIX = Complex(cos(x), sin(x))
let eNegIX = Complex(cos(x), -sin(x))
let scaledSin = (Complex(expNeg2y, 0.0) * ePosIX - eNegIX) / Complex(0.0, 2.0)

let logPrefactor =
    s * Complex(log(2.0), 0.0) +
    (s - Complex(1.0, 0.0)) * Complex(log(Double.pi), 0.0) +
    logGamma(oneMinusS) +
    Complex(y, 0.0)

return Complex.exp(logPrefactor) * scaledSin * zetaReflected
```

Finally, Schwarz reflection symmetry `ζ(s̄) = conj(ζ(s))` handles `Im(s) < 0` automatically.

---

## Interactive Visualizations in SwiftUI

Using SwiftUI `Canvas` and multi-threaded `CGImage` rendering (`DispatchQueue.concurrentPerform`), the macOS app renders four views:

### 1. Critical Line: ζ(σ + it)

Plots `Re(ζ)`, `Im(ζ)`, and `|ζ|` along the critical line `Re(s) = 1/2`. You can drag the `σ` slider off `0.5` to watch the nontrivial zeros immediately lift off the horizontal axis.

![Critical Line Graph](https://raw.githubusercontent.com/erkekin/riemann-zeta-swift/main/screenshots/critical-line.png)

### 2. Complex Plane Domain Coloring

Maps every pixel `s = σ + it` to a color where **hue** encodes the phase `arg(ζ(s))` and **lightness + logarithmic contours** encode the magnitude `|ζ(s)|`. Zeros appear as dark pinwheels lined up along `Re(s) = 1/2`, while the simple pole at `s = 1` glows bright white.

![Complex Plane Domain Coloring](https://raw.githubusercontent.com/erkekin/riemann-zeta-swift/main/screenshots/domain-coloring.png)

### 3. Critical Line Spiral

Plots the parametric curve `(Re ζ(1/2 + it), Im ζ(1/2 + it))` colored by `t`. Every loop passes straight through the origin `(0, 0)` at each nontrivial zero (`t ≈ 14.1347, 21.0220, 25.0109, ...`).

![Critical Line Spiral](https://raw.githubusercontent.com/erkekin/riemann-zeta-swift/main/screenshots/critical-spiral.png)

### 4. Real Axis: ζ(x)

Shows the analytic continuation across the real line with labeled landmarks: the pole at `x = 1`, `ζ(2) = π²/6`, `ζ(0) = -1/2`, `ζ(-1) = -1/12`, and trivial zeros at `-2, -4, -6`.

![Real Axis Graph](https://raw.githubusercontent.com/erkekin/riemann-zeta-swift/main/screenshots/real-axis.png)

---

## Verifying Accuracy with Swift Testing

The `RiemannZetaCoreTests` suite verifies:
- Known real values: `ζ(2) = π²/6` and `ζ(4) = π⁴/90`
- Analytic continuation: `ζ(1/2)`, `ζ(0) = -1/2`, `ζ(-1) = -1/12`, `ζ(-3) = 1/120`, `ζ(-5) = -1/252`
- Trivial zeros at negative even integers and the simple pole at `s = 1`
- The first 10 nontrivial zeros on `Re(s) = 1/2` (`|ζ(0.5 + it)| < 1e-10`)
- Conjugate symmetry and continuity across the `Re(s) = -0.5` reflection boundary

---

## Try It Yourself

```bash
git clone https://github.com/erkekin/riemann-zeta-swift.git
cd riemann-zeta-swift
swift test
swift run
```

Check out the full repository on GitHub: [github.com/erkekin/riemann-zeta-swift](https://github.com/erkekin/riemann-zeta-swift)
