Skip to content
Justin SilverTECHNOLOGY, TRAVEL & EVERYTHING IN BETWEEN

Programming

Proving loudspeaker math with Lean 4

November 23, 2026

Proving Loudspeaker Math with Lean 4 article card comparing a sampled grid 36% overstatement against the 160-bit interval solver and Lean 4 decide +kernel verification

I have been building audio apps lately, including Subchecker for parametric subwoofer enclosure design and cut-list planning, dsSound3D for 3D speaker placement and interference modeling, and Voicebox DS for local narration. Once Subchecker needed sealed alignments, folded and tapered port tuning, DSP protection checks, and impedance comparisons, keeping all of that electroacoustic math buried inside one UI stopped making sense.

I pulled the core solvers out into a standalone, zero-dependency TypeScript package called @0xdoublesharp/electroacoustics. It takes SI units, runs in Node.js 22+ and browsers, and handles sealed boxes, lumped vents, multi-section tapered Webster ducts, passive radiators, LR24/BW24 and biquad filter chains, operating limits, and bounded impedance fitting.

What broke when I started checking the math closely

The first version worked for ordinary cabinets and already had 100% test coverage. Then I started pushing edge cases and writing independent higher-precision references, and seven real bugs showed up.

The largest one was headroom estimation. Evaluating cone travel, port Mach, thermal limits, and amplifier ceilings on a sampled frequency grid looks fine on a plot, until you add a narrow peaking EQ between samples. With a 51 Hz, Q = 60 boost and a 20 V RMS amplifier ceiling across 30 to 80 Hz, a coarse sampled check reported 20.00 V when the true safe drive was 14.71 V, a 36% overstatement.

Voltage ceiling plot across 30 to 80 Hz showing a 51 Hz Q=60 peaking EQ where a sampled grid overstates safe drive by 36% while interval boxes enclose the continuous ceiling within 0.1 dB

Six other numerical and contract issues turned up in the same audit:

  • Complex division underflow and overflow: floating-point complex division zeroed subnormal cases like div(c(Number.MIN_VALUE, 1), c(0, 0.5)) or overflowed early. It now scales to exact integers, cancels the common power of two, and rounds ties-to-even to binary64.
  • Infinite SPL at extreme pressure ratios: dividing pressure magnitude by 20 µPa before calling Math.log10 overflowed to Infinity on extreme scales. Scaling in log space keeps SPL finite across the binary64 range.
  • Biquad cancellation near DC, Nyquist, and poles: biquadTransfer now evaluates the centered versine form in 160-bit dyadic interval arithmetic and guarantees per-component error within 2⁻⁴⁰ × max(1, |exact|) or throws RangeError.
  • Silent nonfinite resonance values: added finite angular-frequency guards and split the square roots in passiveRadiatorResonanceHz so small compliances do not trigger spurious overflow.
  • Silent root status on duct bisection: solveDuctLengthForTuning previously returned 'root' after 80 steps even when the bracket was wider than toleranceM. It now returns the final bracket, step count, and 'budget-exhausted' or 'resolution-limit' when it stops early.
  • Uncertified impedance-fit status: forward finite differences could conflate bound-constrained, stalled, and weakly identified fits. The fitter now runs 160-bit forward-mode dual-dyadic automatic differentiation at the returned point to check exact residuals, projected KKT gradients, and sensitivity rank.

Why I added Lean 4 formal verification

Fixing those bugs with interval arithmetic gave me something better than point estimates: JSON-serializable certificates. A resolved call to analyzeBandOutputLimit does not just return a safe voltage. It returns the exact frequency spans, witness frequency, safe voltage, upper voltage, and dB gap so an independent checker can verify every frequency in the closed interval [minHz, maxHz].

Once the certificates existed, checking them inside Lean 4 became practical. As far as I can tell, there are no other public loudspeaker or electroacoustics libraries with continuous-band interval certificates or machine-checked proofs. Python kits like electroacPy and SpeAcouPy, web apps like OpenISD, and desktop tools like WinISD, Hornresp, and VituixCAD all evaluate sampled grids in floating point. Having a proof assistant independently verify the physics and the bounds from the shipped npm archive felt worth building all the way out.

Verification and capability matrix for @0xdoublesharp/electroacoustics showing all seven solver domains, 160-bit dyadic checks, Lean 4 kernel replays, and ecosystem comparison

How the runtime checks connect to the Lean kernel

At runtime, TypeScript stays fast and dependency-free. analyzeBandOutputLimit, boundDuctPathTuning, boundDuctPathPeakVelocityRatio, fitDriverImpedance, and fitEnclosureImpedance self-verify their certificates in 160-bit dyadic interval arithmetic before returning them. Every verifier fails closed on tampered spans, mismatched requests, or out-of-range bounds.

Two-panel loudspeaker plot comparing sealed and vented small-signal SPL at 2.83 V RMS above the vented single-tone output ceiling with active cone, voltage, and thermal limits

For independent verification, three replay scripts take a saved JSON certificate, validate it against the recorded request, encode every finite binary64 number as an exact binary rational, and emit a Lean 4 theorem proved by decide +kernel. Running npm run verify:formal builds the npm tarball, installs it into a clean consumer, extracts eight real certificates from that installed archive, and checks all eight inside Lean 4:

  • Continuous-band headroom: peaking EQ (52 spans, 22.6 s), uncorrected straight duct (11.4 s), and a multi-section conical and exponential duct with both mouth corrections and an active Mach limit (68.4 s).
  • Distributed duct bounds: first positive pole-free tuning with earlier-root exclusion back to DC (11.3 s) and interior standing-wave peak airspeed across a two-section tapered duct (23.9 s).
  • Impedance-fit diagnostics: paired driver fit (28.9 s), full-rank enclosure fit (9.1 s), and a poorly identified sparse sweep with a certified weak-sensitivity direction (7.7 s).
Paired free-air and added-mass impedance sweeps with synthetic measurement noise, initial and fitted model curves, and relative fit residuals from 8 to 300 Hz
import { analyzeBandOutputLimit, verifyBandOutputCertificate } from '@0xdoublesharp/electroacoustics'

const options = {
  minHz: 30,
  maxHz: 80,
  maxAmplifierVoltageRms: 20,
  filter: {
    digital: {
      sampleRateHz: 48000,
      stages: [{ kind: 'peaking', frequencyHz: 51, q: 60, gainDb: 20 * Math.log10(1.36) }],
    },
  },
} as const

const band = analyzeBandOutputLimit(sealedInput, options)
if (band.status === 'resolved' && band.certificate) {
  console.log(band.safeInputVoltageRms, band.errorBoundDb)
  console.log(verifyBandOutputCertificate(sealedInput, options, band.certificate))
}

What the proofs do and do not claim

In total, Audit.lean audits 629 theorems across 17 Lean modules, and ElectroacousticsReplay.lean runs 24 axiom checks. Every proof and every installed-archive kernel replay depends strictly on Lean’s standard axioms: propext, Classical.choice, and Quot.sound. There are zero sorry placeholders, and all project Lean files compile with warnings treated as errors.

Keeping the boundaries clear matters as much as the proofs. The theorems apply to the linear small-signal circuit, lumped cavity, and rigid one-dimensional duct models. Impedance-fit replay proves local KKT stationarity and sensitivity rank at the returned point, leaving global optimality outside scope, and distributed-duct impedance fits verify in the 160-bit dyadic TypeScript checker while Lean replays driver, sealed, lumped-vented, and passive-radiator fits. To check the physical model against real hardware, the high-precision test suite also compares modeled resonance and impedance peaks against three published sealed, vented, and passive-radiator test fixtures.

# Run typecheck, 100% coverage suite, build, and npm archive check
npm run check

# Build Lean 4 proofs, audit all 629 theorems, and kernel-replay all 8 archive certificates
npm run verify:formal

The electroacoustics library page has the workflow and package links. The full source, solver accuracy contracts, and Lean 4 proof inventory are on GitHub, and the package is on npm.