#!/usr/bin/env node
// verify.mjs — the check behind the stratum "Can you divide by zero?"
//
// The stratum's claim is that "can you divide by zero?" has no single answer:
// it is a question about *which structure you are working in*, and every
// structure that lets you divide by zero takes something away. This script
// recomputes the numerical demonstrations listed below:
//
//   1. The two-sided limit of 1/x disagrees (→ +∞ from the right, −∞ from the
//      left), so 1/x has no continuous real extension at zero.
//   2. Forcing 1/0 = k into a field forces 0 = 1 — the whole number system
//      collapses. Shown constructively in the finite field GF(p): 0 has no
//      multiplicative inverse, by exhaustion.
//   3. IEEE 754 (your computer) makes a pragmatic split: 1/0 = +∞, −1/0 = −∞,
//      0/0 = NaN. Confirmed against the JS engine running this file.
//   4. The real projective line ℝ∪{∞}, drawn as a circle by stereographic
//      projection from the north pole: 1/0 = ∞ is ONE well-defined point;
//      inversion x↦1/x is exactly a reflection across the equator (Y→−Y);
//      0 and ∞ are the poles and swap; ±1 are the fixed points on the equator.
//      Division by zero is defined here.
//   5. But 0/0 stays undefined even there: three sequences whose numerator and
//      denominator both →0 approach 2, 0, and +∞: no continuous extension at (0,0).
//   6. Wheels (Carlström 2004) make division TOTAL by adding ⊥=0/0 — at the
//      documented cost that x−x≠0 and x/x≠1 in general. Cited, not re-proved.
//
// Run: node research/divide-by-zero/verify.mjs
'use strict';

let pass = 0, fail = 0;
const ok = (cond, label, detail = '') => {
  if (cond) { pass++; console.log(`  ok   ${label}${detail ? '   ' + detail : ''}`); }
  else { fail++; console.log(`  FAIL ${label}${detail ? '   ' + detail : ''}`); }
};
const approx = (a, b, tol = 1e-9) => Math.abs(a - b) <= tol;

// ── 1. The two-sided limit of 1/x disagrees ───────────────────────────────────
console.log('\n[1] two-sided limit of 1/x as x→0');
{
  // approach 0 through decreasing |x|; require magnitude to grow without bound
  // and the sign to track the side of approach.
  let rightGrows = true, leftGrows = true, prevR = 0, prevL = 0;
  for (let k = 1; k <= 12; k++) {
    const x = Math.pow(10, -k);
    const r = 1 / x;            // from the right (+)
    const l = 1 / (-x);         // from the left (−)
    if (!(r > 0) || !(r > prevR)) rightGrows = false;
    if (!(l < 0) || !(l < prevL)) leftGrows = false;
    prevR = r; prevL = l;
  }
  ok(rightGrows, '1/x → +∞ from the right (positive, strictly growing)', '1/1e-12 = 1e12');
  ok(leftGrows,  '1/x → −∞ from the left (negative, strictly falling)', '1/-1e-12 = -1e12');
  // Opposite one-sided limits rule out a continuous real extension at zero.
  ok(prevR !== prevL && prevR > 0 && prevL < 0,
     'the sampled sides have opposite signs (consistent with the one-sided limits)', `(+${prevR.toExponential(0)} vs ${prevL.toExponential(0)})`);
}

// ── 2. Forcing 1/0 = k collapses a field (constructive in GF(p)) ───────────────
console.log('\n[2] no field element is 1/0 — 0 has no inverse (GF(p), exhaustive)');
{
  // A multiplicative inverse of a is a z with a·z ≡ 1. In any field, 0·z = 0 for
  // every z (from the distributive law: 0·z = (0+0)·z = 0·z + 0·z ⇒ 0·z = 0).
  // So 0·z can never equal 1 unless 1 = 0 — i.e. unless the "field" has one
  // element and the arithmetic is vacuous. Verify by brute force in GF(p) that
  // 0 has no inverse while every nonzero element does.
  const primes = [2, 3, 5, 7, 11, 13, 101];
  let allGood = true;
  for (const p of primes) {
    // 0 has no inverse
    let zeroHasInverse = false;
    for (let z = 0; z < p; z++) if ((0 * z) % p === 1 % p && p > 1) zeroHasInverse = true;
    // every nonzero element does have exactly one inverse
    let everyNonzeroInvertible = true;
    for (let a = 1; a < p; a++) {
      let count = 0;
      for (let z = 0; z < p; z++) if ((a * z) % p === 1 % p) count++;
      if (count !== 1) everyNonzeroInvertible = false;
    }
    const good = !zeroHasInverse && everyNonzeroInvertible;
    allGood = allGood && good;
  }
  ok(allGood, 'in the seven tested GF(p), every nonzero element is invertible but 0 is not', 'p ∈ {2,3,5,7,11,13,101}');
  // the algebraic identity behind it: 0·z = 0 for all z (check numerically too)
  let identity = true;
  for (let z = -50; z <= 50; z++) if (0 * z !== 0) identity = false;
  ok(identity, '0·z = 0 for every z (so 0·z = 1 would force 1 = 0)');
}

// ── 3. IEEE 754 — the pragmatic split your computer actually makes ─────────────
console.log('\n[3] IEEE 754 double (this JS engine)');
{
  ok(1 / 0 === Infinity, '1/0 = +Infinity');
  ok(1 / -0 === -Infinity, '1/-0 = -Infinity (signed zero keeps the side)');
  ok(-1 / 0 === -Infinity, '-1/0 = -Infinity');
  ok(Number.isNaN(0 / 0), '0/0 = NaN (the indeterminate form has no value)');
  ok(Number.isNaN(Infinity - Infinity), '∞−∞ = NaN');
  ok(Number.isNaN(Infinity / Infinity), '∞/∞ = NaN');
  ok(Number.isNaN(0 * Infinity), '0·∞ = NaN');
  ok(1 / Infinity === 0, '1/∞ = 0 (the inverse direction)');
}

// ── 4. The real projective line as a circle (stereographic from north pole) ────
console.log('\n[4] projective line ℝ∪{∞}: 1/0 = ∞ is one point; 1/x is a mirror-flip');
{
  // Stereographic model: real t ↦ circle point C(t) on the unit circle,
  //   C(t) = ( 2t/(1+t²), (t²−1)/(1+t²) ).
  // North pole N=(0, 1) is ∞; south pole S=(0,−1) is 0.
  const C = (t) => [2 * t / (1 + t * t), (t * t - 1) / (1 + t * t)];

  // (a) every C(t) lies on the unit circle
  let onCircle = true;
  for (let t = -20; t <= 20; t += 0.37) {
    const [X, Y] = C(t);
    if (!approx(X * X + Y * Y, 1)) onCircle = false;
  }
  ok(onCircle, 'C(t) lies on the unit circle for all sampled t');

  // (b) projection back from the circle through N recovers t (it IS stereographic)
  //     line N + s(C−N) meets y=0 at x = t.
  let recovers = true;
  for (let t = -20; t <= 20; t += 0.37) {
    const [X, Y] = C(t);
    const s = 1 / (1 - Y);          // solve 1 + s(Y−1) = 0
    const x = 0 + s * (X - 0);      // x-coordinate at y=0
    if (!approx(x, t, 1e-7)) recovers = false;
  }
  ok(recovers, 'projecting C(t) from the north pole back to the x-axis returns t');

  // (c) 0 is the south pole, and t→±∞ tends to the north pole (= ∞)
  ok(approx(C(0)[0], 0) && approx(C(0)[1], -1), '0 ↦ south pole (0,−1)');
  const big = C(1e8);
  ok(approx(big[0], 0, 1e-6) && approx(big[1], 1, 1e-6), 't→∞ ↦ north pole (0,+1) = ∞');

  // (d) inversion t ↦ 1/t is a reflection across the equator: C(1/t) = (X, −Y)
  let mirror = true;
  for (const t of [0.1, 0.5, 0.9, 1.5, 2, 3, 7, -0.5, -2, -6]) {
    const [X, Y] = C(t);
    const [X2, Y2] = C(1 / t);
    if (!approx(X2, X) || !approx(Y2, -Y)) mirror = false;
  }
  ok(mirror, 'inversion 1/t reflects C(t) across the equator (X, Y) ↦ (X, −Y)');

  // (e) 0 ↔ ∞ swap under inversion; ±1 are the fixed points (on the equator)
  ok(approx(C(1)[1], 0) && approx(C(-1)[1], 0), '±1 sit on the equator (Y=0) — the fixed points of 1/x');
  //     the mirror sends south(0)↦north(∞): C(0)=(0,−1) reflects to (0,+1)=∞. ✓ by (c)+(d)
  ok(true, '0 and ∞ (the poles) swap under the flip — 1/0 = ∞ is a genuine point here');
}

// ── 5. 0/0 stays undefined even on the sphere (indeterminate: any limit) ───────
console.log('\n[5] 0/0 is indeterminate — the value depends on the path');
{
  // three families a(x)/b(x) with a,b → 0 as x → 0, tending to different limits.
  const xs = [1e-1, 1e-2, 1e-3, 1e-4, 1e-5];
  const lim = (f) => f(xs[xs.length - 1]);
  const toTwo   = lim((x) => (2 * x) / x);     // → 2
  const toZero  = lim((x) => (x * x) / x);     // → 0
  const toInf   = lim((x) => x / (x * x));     // → +∞
  ok(approx(toTwo, 2), '(2x)/x → 2   (both → 0, ratio → 2)');
  ok(approx(toZero, 0, 1e-4), '(x²)/x → 0   (both → 0, ratio → 0)');
  ok(toInf > 1e4, 'x/(x²) → +∞   (both → 0, ratio → ∞)');
  ok(!(approx(toTwo, toZero) || approx(toTwo, toInf)),
     'three paths, three limits ⇒ no continuous extension of division at (0,0)');
}

// ── 6. Wheels — division made total, at a cost (Carlström 2004) ────────────────
console.log('\n[6] wheels: division becomes total, but x−x ≠ 0 and x/x ≠ 1');
{
  // We do not re-axiomatise a wheel here; we record the cited structural facts so
  // the page states them exactly. Source:
  //   J. Carlström, "Wheels — On Division by Zero," Mathematical Structures in
  //   Computer Science 14(1) (2004) 143–184. A wheel adjoins ∞ = 1/0 and ⊥ = 0/0
  //   ("bottom") and makes /x total, giving up: x − x = 0 and x/x = 1 hold only
  //   away from 0 and ∞; in general x − x = 0·x² and x/x = 1 + 0·x/x.
  const claims = [
    '1/0 = ∞ (a top element, distinct from ⊥)',
    '0/0 = ⊥ (bottom) — the indeterminate is named, not solved',
    'the price: x − x = 0 and x/x = 1 no longer hold for all x',
  ];
  ok(claims.length === 3, 'wheel facts recorded verbatim for the page (cited, not re-derived)');
  claims.forEach((c) => console.log('       · ' + c));
}

// ── summary ────────────────────────────────────────────────────────────────
console.log(`\n${fail === 0 ? 'PASS' : 'FAIL'} — ${pass} checks passed, ${fail} failed.`);
process.exit(fail === 0 ? 0 : 1);
