Dev.to WebDev 🛠 Dev 👁 0 📖 3 min read

Building 9 verified calculators in vanilla JS: symbolic derivatives, Simpson integrals and the $-collision trap

Building a calculator is easy. Building one that never disagrees with your textbook is not. This is a build-log from shipping nine math tools — mixed-number arithmetic, FOIL expansion, the discriminant, Gaussian eliminat

Building a calculator is easy. Building one that never disagrees with your textbook is not. This is a build-log from shipping nine math tools — mixed-number arithmetic, FOIL expansion, the discriminant, Gaussian elimination, Fourier series, gradients (∇f), diagonals, and two name generators — where every answer is checked against Python ground truth before the button ships.

1. The ground rule: no answer ships unverified

Each tool is driven headlessly (Playwright over CDP) with known inputs, and the on-page output is compared to an independent Python computation. Examples from the actual test run:

  • 2 3/4 + 1 1/2 → 4 1/4, improper 17/4, decimal 4.25
  • (3x + 2)(x − 5) → 3x² − 13x − 10
  • x² − 5x + 6 → Δ = 1, roots 3 and 2; cubic x³ − 6x² + 11x − 6 → Δ = 4 (three distinct real roots)
  • 3×3 Gaussian elimination with partial pivoting → x = (−0.40625, 2.5625, 1.875) — plus a "No solution" row of 0 = 9 correctly detected
  • x² on [−π, π] → a₀/2 = 3.289868 = π²/3, parity auto-detected as even, a₁ = −4 in the table

If the browser output and Python disagree, the tool does not ship. That single rule caught two real bugs during development (one of them is #4 below).

2. One expression engine, three jobs

The Fourier series calculator and the gradient calculator share one tiny engine: a tokenizer, a recursive-descent parser producing an AST, and three consumers — numeric evaluation, symbolic differentiation, and a small simplifier.

// d/dx of a product: (uv)' = u'v + uv'
if (n.op === '*') return add(mul(D(n.l, v), n.r), mul(n.l, D(n.r, v)));
// chain rule for general u^v: u^v · (v'·ln u + v·u'/u)
if (n.op === '^') {
  if (b.t === 'num') return mul(mul(C(b.v), B('^', a, C(b.v - 1))), da);
  return mul(B('^', a, b), add(mul(db, F('ln', a)), div(mul(b, da), a)));
}

The derivative is printed as an algebraic expression (∂f/∂x = 2*x*y) before any number is substituted — because the whole point is checking your hand work, not copying a decimal. For f = x²y at (2, 3) the tool shows ∇f = (12, 4), |∇f| ≈ 12.6491, and the directional derivative along (1, 0) as an explicit dot product.

3. Numerics: Simpson, and honesty about Gibbs

The Fourier coefficients use composite Simpson with 4,000 subintervals: aₙ = (1/L)∫f(x)cos(nπx/L)dx. For smooth functions that is ~10⁻⁸ relative error, which is why textbook checks match to every digit shown. The tool also prints the max error of the N-term partial sum on the interval — and does not hide the Gibbs phenomenon: for x² at N = 6 the worst error is ≈ 0.61 (about 6% of π²) at the endpoints, and the FAQ says so instead of promising magic convergence.

4. The bug worth your attention: the global $ collision

Every tool script was self-contained… until it wasn't. The site's shared main.js (loaded after inline scripts) declares its own global var $ = function(i){ return document.getElementById(i) } — no jQuery-style # stripping. Our handlers called $('#go'). Element lookups at load time worked, so listeners registered fine; but at event time, main.js had replaced $, getElementById('#go') returned null, and the first null.addEventListener blew up inside the handler. Classic late-binding footgun.

The fix is an IIFE with a local helper on every tool script:

(function () {
  var $ = function (i) { return document.getElementById(String(i).replace(/^#/, '')) };
  // ... entire tool, its listeners, its state — invisible to the page's other scripts
})();

Lesson: on any site with legacy globals, inline feature scripts must never read a global that another script also writes. hoisting gets you definitions, not immutability.

5. Why the boring ones are the hardest

The mixed number calculator looks trivial until you handle -2 1/2 (sign applies to the whole quantity), LCD vs GCD in the right places, and converting back with a correct remainder. The Gaussian elimination tool needs partial pivoting for stability, rank(A) vs rank([A|b]) for the three solution cases, and det(A) = pivot product × (−1)^swaps. Verified math is mostly careful bookkeeping, not cleverness.

6. The verification harness

The harness serves the static site locally, opens each page, fills inputs, clicks, and asserts against Python-computed expectations — 30+ assertions across the nine tools, including error paths (vertical-line slope, a = 0 discriminants, division by a zero fraction). Everything runs on request; the full catalog with per-tool FAQ answers is published as llms.txt and tools.json for anyone building on top of it.

Disclosure (per the DEV Code of Conduct): this article and the tools it describes were built with AI assistance; every claim above was verified by automated headless tests against independent Python computations, and the math checks are reproducible from the linked tools.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.