Test a Swift Linear Solver with Pivoting and Residuals

When you move a calibration or fitting module written on Windows to a cloud Mac for compilation, the first thing to check is not speed: it is whether the computed solution satisfies the original equations. An elimination routine that never swaps rows to select a pivot may pass ordinary samples, then fail as soon as the first diagonal entry is zero. Here, we build a small linear-system acceptance test in a standalone Swift file, with no dependencies on UI, networking, or code-signing settings.

Define the solver contract first

The goal is to solve Ax=b. The inputs are a nonempty square matrix and a vector of matching length, with Double elements. This article caps the dimension at 128 as a resource budget for the test tool, not as a hardware limit. Empty inputs, dimension mismatches, nonfinite values, and pivots that the chosen numerical policy cannot handle reliably must all produce explicit failures.

First, scale each row by its largest absolute coefficient, then perform elimination with partial pivoting. Apply the same scaling to the right-hand side; do not scale only the matrix. The pivot threshold is 1e-12, which illustrates the precision policy used here rather than defining a universal constant.

Rejecting a small pivot means “this policy will not continue solving,” not that the matrix has been proved exactly singular. Likewise, a small residual does not guarantee an accurate solution.

Use a validated numerical library for large-scale production computations. This small implementation explains the test boundaries and makes it easy to cross-check a production solver.

Implement row scaling and partial pivoting

Save the following code as solver.swift. The function preserves the original inputs and performs elimination on internal copies, so later residual checks can still use the original equations. The pivot search covers all remaining rows in the current column, and each row swap also swaps the corresponding right-hand-side entries.

import Foundation

enum SolveError: Error {
    case invalidInput
    case numericalFailure
}

func solve(_ a: [[Double]], _ b: [Double]) throws -> [Double] {
    let n = a.count
    guard (1...128).contains(n),
          b.count == n,
          a.allSatisfy({ $0.count == n }),
          a.allSatisfy({ $0.allSatisfy { $0.isFinite } }),
          b.allSatisfy({ $0.isFinite }) else {
        throw SolveError.invalidInput
    }

    var m = a
    var rhs = b
    for i in 0..<n {
        let scale = m[i].map { abs($0) }.max()!
        guard scale > 0 else { throw SolveError.numericalFailure }
        for j in 0..<n {
            m[i][j] /= scale
        }
        rhs[i] /= scale
        guard rhs[i].isFinite else {
            throw SolveError.numericalFailure
        }
    }

    for k in 0..<n {
        let pivot = (k..<n).max {
            abs(m[$0][k]) < abs(m[$1][k])
        }!
        guard abs(m[pivot][k]) > 1e-12 else {
            throw SolveError.numericalFailure
        }
        if pivot != k {
            m.swapAt(k, pivot)
            rhs.swapAt(k, pivot)
        }
        for i in (k + 1)..<n {
            let factor = m[i][k] / m[k][k]
            m[i][k] = 0
            for j in (k + 1)..<n {
                m[i][j] -= factor * m[k][j]
                guard m[i][j].isFinite else {
                    throw SolveError.numericalFailure
                }
            }
            rhs[i] -= factor * rhs[k]
            guard rhs[i].isFinite else {
                throw SolveError.numericalFailure
            }
        }
    }

    var x = Array(repeating: 0.0, count: n)
    for i in (0..<n).reversed() {
        var value = rhs[i]
        for j in (i + 1)..<n {
            value -= m[i][j] * x[j]
        }
        x[i] = value / m[i][i]
        guard x[i].isFinite else {
            throw SolveError.numericalFailure
        }
    }
    return x
}

Do not replace every failure with a zero vector. A zero vector might happen to pass downstream application range checks, disguising a numerical failure as a valid result. Propagate the error type up the call chain and let the application decide whether to reject the calculation or use an explicit fallback.

Test failure boundaries with known solutions

Append the following assertions to the same file. The first system deliberately has a zero in the top-left corner and a known solution of [1, 2], directly exposing a missing pivot swap. The second separates the row magnitudes by many orders of magnitude to check that scaling also updates the right-hand side.

let a = [[0.0, 2.0], [1.0, 3.0]]
let b = [4.0, 7.0]
let x = try solve(a, b)
precondition(abs(x[0] - 1) < 1e-10)
precondition(abs(x[1] - 2) < 1e-10)

let scaled = try solve(
    [[0, 2e-9], [1e9, 3e9]],
    [4e-9, 7e9]
)
precondition(abs(scaled[0] - 1) < 1e-10)
precondition(abs(scaled[1] - 2) < 1e-10)

func rejects(_ a: [[Double]], _ b: [Double]) -> Bool {
    do {
        _ = try solve(a, b)
        return false
    } catch {
        return true
    }
}

precondition(rejects([], []))
precondition(rejects([[1, 2]], [1]))
precondition(rejects([[1]], []))
precondition(rejects([[1, 2], [2, 4]], [3, 6]))
precondition(rejects([[Double.nan]], [1]))
precondition(rejects([[1]], [Double.infinity]))

These assertions check that the inputs must be rejected, but do not yet verify the specific error types. Once the checks are integrated into a test target, assert input errors and numerical failures separately so that future changes cannot silently misclassify every failure as an input-format error.

Also add a matrix of order one, a row of all-zero coefficients, and samples just above and below the threshold. For threshold samples, record the pivot after scaling rather than guessing the outcome from the original matrix’s diagonal entries.

Check residuals against the original equations

Substitute the computed solution into the original equations to calculate r=Ax-b. Record the following normalized measure:

η = ||r||∞ / (||A||∞ × ||x||∞ + ||b||∞)

The vector infinity norm is the largest absolute element; the matrix infinity norm is the largest absolute row sum. Do not confuse the matrix norm with the largest individual element, and do not substitute the upper-triangular matrix produced by elimination for the original matrix.

In this example, the solution is [1, 2], substitution gives [4, 7], and the residual is zero. Real tests should combine absolute and relative tolerances rather than require bit-for-bit equality for every floating-point sample. Handle a zero denominator separately: pass only if the residual is also zero.

Fail if a norm or residual calculation produces a nonfinite value. Do not skip the comparison merely because division yields an exceptional value. Extreme magnitudes also require a stable, scaled norm implementation; the basic samples in this fixture stay within a range that is safe to compute.

An ill-conditioned system can have a very small residual while its computed solution differs substantially from the known solution. Keep both the known-solution error and the normalized residual, and add a condition-number estimate when needed.

Make the acceptance run repeatable on the cloud Mac

In the remote desktop’s terminal, change to the directory containing the file and run both development and optimized builds:

set -eu
mkdir -p .solver-build
xcrun swiftc --version > .solver-build/toolchain.txt
xcrun swiftc -Onone solver.swift -o .solver-build/check-debug
.solver-build/check-debug
xcrun swiftc -O solver.swift -o .solver-build/check-release
.solver-build/check-release

An assertion failure should produce a nonzero exit status, stopping the script immediately. Do not use -Ounchecked, which removes these checks. When integrating the solver into the application, move the assertions into a test target and also run tests in the iOS simulator. Passing a macOS command-line check does not mean every check has passed on the target platform.

For each run, save the commit ID, compiler version, sample IDs, maximum solution error, and normalized residual. When adjusting the threshold, recheck both accepted and rejected samples; “fewer failures” is not evidence of correctness. The final acceptance criteria are stable input boundaries and explainable errors—not a solver that always returns a set of numbers.

Frequently asked questions

Does a small residual guarantee an accurate solution

No. An ill-conditioned matrix can amplify input errors even when the residual is small. Add known-solution fixtures and a condition estimate.

Does rejecting a small pivot prove singularity

No. The example applies its threshold after row scaling. Rejection reflects the chosen numerical policy, not an exact mathematical rank test.

Move your next build to a cloud Mac

Rent a dedicated physical Mac and use its macOS desktop in your browser. Choose a daily, weekly, monthly, or quarterly plan; it stops at the end of your term unless you renew.

Get a Mac

Get a Mac and get back to your project

A dedicated physical Mac, accessible in your browser. Choose a daily, weekly, monthly, or quarterly rental; it stops at the end of your term unless you renew.