#!/usr/bin/env node
// Verification for the portal "The Common Measure".
//
// The portal's claim: three strata — Incommensurable (√2), The Comma (the
// circle of fifths), The Most Irrational Number (φ) — are three faces of ONE
// algorithm: anthyphairesis = the Euclidean algorithm on two magnitudes =
// the continued fraction. A pair of magnitudes shares a common measure iff
// the algorithm terminates; the sequence of quotients is the continued
// fraction; its truncations (convergents) are the best rational approximations.
//
// Everything the page asserts numerically is recomputed here from scratch.
// Run: node research/the-common-measure/verify.mjs   (exit 0 = all pass)

let pass = 0, fail = 0;
const eq = (name, got, want, tol = 0) => {
  const ok = typeof want === 'bigint' || typeof want === 'string'
    ? String(got) === String(want)
    : Math.abs(got - want) <= tol;
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${name}\n        got ${got}${ok ? '' : `  want ${want}${tol ? ` ±${tol}` : ''}`}`);
  ok ? pass++ : fail++;
};

// ---------------------------------------------------------------------------
// 0.  Continued-fraction convergents via the standard recurrence (BigInt).
//     h_n = a_n h_{n-1} + h_{n-2},  k_n = a_n k_{n-1} + k_{n-2}.
// ---------------------------------------------------------------------------
function convergents(a) {
  let hm1 = 1n, hm2 = 0n, km1 = 0n, km2 = 1n;
  const out = [];
  for (const ai of a) {
    const A = BigInt(ai);
    const h = A * hm1 + hm2, k = A * km1 + km2;
    out.push([h, k]);
    hm2 = hm1; hm1 = h; km2 = km1; km1 = k;
  }
  return out;
}

// Continued fraction of a real x to n terms, via the Euclidean/anthyphairesis
// step: a = floor(x); x <- 1/(x - a). (Float — good for the first several terms.)
function cf(x, n) {
  const a = [];
  for (let i = 0; i < n; i++) {
    const ai = Math.floor(x);
    a.push(ai);
    const frac = x - ai;
    if (frac < 1e-12) break;
    x = 1 / frac;
  }
  return a;
}

console.log('\n=== I.  √2 — the diagonal that is no fraction ===\n');
// √2's continued fraction is [1; 2,2,2,...] (periodic). Verify the algorithm
// reproduces it, and that the convergents square toward 2.
{
  const a = cf(Math.SQRT2, 10);
  eq('√2 CF starts [1;2,2,2,2,2,...]', a.slice(0, 6).join(','), '1,2,2,2,2,2');
  const cv = convergents([1, 2, 2, 2, 2, 2]);  // 1/1,3/2,7/5,17/12,41/29,99/70
  eq('√2 convergent #4 = 17/12', `${cv[3][0]}/${cv[3][1]}`, '17/12');
  eq('√2 convergent #6 = 99/70', `${cv[5][0]}/${cv[5][1]}`, '99/70');
  // (99/70)^2 = 9801/4900 = 2.00020408...  — straddles 2, never equals it.
  const r = 99 / 70;
  eq('(99/70)^2 ≈ 2 but ≠ 2', r * r, 2.0002, 1e-4);
  // Parity proof, mechanically: if a^2 = 2 b^2 with gcd(a,b)=1 then a,b both even.
  // We don't "run" the proof, but we confirm no small fraction squares to 2:
  let exact = false;
  for (let q = 1; q <= 5000 && !exact; q++)
    for (let p = 1; p <= 2 * q; p++) if (p * p === 2 * q * q) exact = true;
  eq('no fraction p/q with q≤5000 squares to exactly 2', exact, false);
}

console.log('\n=== II.  The fifth that will not close ===\n');
// A perfect fifth is the frequency ratio 3/2; an octave is 2/1. n fifths equal
// m octaves exactly iff (3/2)^n = 2^m, i.e. log2(3/2) = m/n — impossible, since
// 3^n (odd) can never equal a power of 2 (even). So the circle of fifths never
// closes. The SIZE of the near-misses is governed by the continued fraction of
// log2(3/2): its convergents m/n are exactly the good equal temperaments.
{
  // 3^12 vs 2^19 — the Pythagorean comma, in exact integers.
  const p3_12 = 531441n, p2_19 = 524288n;
  eq('3^12 = 531441', 3n ** 12n, p3_12);
  eq('2^19 = 524288', 2n ** 19n, p2_19);
  eq('they differ by 7153', p3_12 - p2_19, 7153n);

  // log2(3) to 31 digits (OEIS A020857) → log2(3/2) = log2(3) − 1.
  const LOG2_3 = 1.5849625007211561814537389439478;
  const L = LOG2_3 - 1;                       // log2(3/2) = 0.58496250072...
  eq('log2(3/2) ≈ 0.5849625', L, 0.5849625007, 1e-9);

  // Pythagorean comma in cents = 1200 · log2(3^12 / 2^19)
  //   = 1200 · (12·log2(3/2) − 7)
  const commaCents = 1200 * (12 * L - 7);
  eq('Pythagorean comma ≈ 23.46 cents', commaCents, 23.460, 0.001);

  // Continued fraction of log2(3/2). Float is reliable here for ~7 terms.
  const a = cf(L, 8);
  eq('log2(3/2) CF = [0;1,1,2,2,3,1,5]', a.slice(0, 8).join(','), '0,1,1,2,2,3,1,5');

  // Its convergents m/n (octaves per fifth) ARE the equal temperaments:
  const cv = convergents(a.slice(0, 8));       // 0/1,1/1,1/2,3/5,7/12,24/41,31/53,179/306
  const conv = cv.map(([h, k]) => `${h}/${k}`);
  eq('convergent → 7/12  (12-tone equal temperament)', conv[4], '7/12');
  eq('convergent → 24/41 (41-EDO)', conv[5], '24/41');
  eq('convergent → 31/53 (53-EDO)', conv[6], '31/53');

  // Closure error of each temperament, in cents:
  //   stack n fifths, ask how far from m octaves: 1200·(n·log2(3/2) − m)
  const closure = (n, m) => 1200 * (n * L - m);
  eq('12 fifths overshoot 7 octaves by the comma (+23.46¢)', closure(12, 7), 23.460, 0.002);
  eq('41 fifths fall short of 24 octaves (−19.84¢)', closure(41, 24), -19.845, 0.01);
  eq('53 fifths overshoot 31 octaves by only +3.62¢', closure(53, 31), 3.615, 0.01);
  // The errors shrink as the convergents climb — and alternate in sign,
  // exactly as continued-fraction convergents must.
  const errs = [closure(12, 7), closure(41, 24), closure(53, 31)].map(Math.abs);
  eq('closure error strictly shrinks 12 → 41 → 53', errs[0] > errs[1] && errs[1] > errs[2], true);
  // The page says how much truer 53 is than 12: the ratio of the two closure misses.
  // (It said "ten times" until 2026-09-29; the ratio is 6.49. Claims pass.)
  eq('53-tone misses by about six and a half times less than 12-tone', errs[0] / errs[2], 6.49, 0.01);
  eq('and alternates sign (over, under, over)',
     Math.sign(closure(12, 7)) === 1 && Math.sign(closure(41, 24)) === -1 && Math.sign(closure(53, 31)) === 1, true);

  // The PAGE frames it as the octave measured against the fifth (both ≥ 1),
  // i.e. the reciprocal: (octave:fifth) = 1/log2(3/2) ≈ 1.70951, CF [1;1,2,2,3,1,5].
  // Now the NUMERATOR of each convergent is the number of fifths (= the EDO).
  const aOct = cf(1 / L, 8);
  eq('octave:fifth CF = [1;1,2,2,3,1,5]', aOct.slice(0, 7).join(','), '1,1,2,2,3,1,5');
  const cvO = convergents([1, 1, 2, 2, 3, 1, 5]).map(([h, k]) => `${h}/${k}`);
  eq('convergent → 12/7  (12 fifths, 7 octaves → 12-EDO)', cvO[3], '12/7');
  eq('convergent → 41/24 (41-EDO)', cvO[4], '41/24');
  eq('convergent → 53/31 (53 fifths, 31 octaves → 53-EDO)', cvO[5], '53/31');
}

console.log('\n=== III.  φ — the number nothing nearly catches ===\n');
// φ's continued fraction is all 1s — the smallest terms possible — so its
// convergents (Fibonacci ratios) approach as slowly as any number's can.
{
  const PHI = (1 + Math.sqrt(5)) / 2;
  const a = cf(PHI, 8);
  eq('φ CF is all 1s', a.slice(0, 7).join(','), '1,1,1,1,1,1,1');
  const cv = convergents([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
  // Convergents are consecutive Fibonacci ratios: 1/1,2/1,3/2,5/3,8/5,13/8,21/13...
  eq('φ convergent #5 = 8/5', `${cv[4][0]}/${cv[4][1]}`, '8/5');
  eq('φ convergent #8 = 34/21', `${cv[7][0]}/${cv[7][1]}`, '34/21');
  // Numerator(n) = denominator(n+1): the Fibonacci shift.
  eq('Fibonacci shift: num(n) = den(n+1)', cv[6][0] === cv[7][1], true);

  // Hurwitz (1891): every irrational has infinitely many p/q with
  // |x − p/q| < 1/(√5 q²); √5 is the best constant, and φ is its worst case.
  // Check φ saturates the bound — its convergents sit RIGHT at 1/(√5 q²):
  //   q² · |φ − p/q|  →  1/√5 = 0.4472...   (from above, never beaten)
  const tail = cv.slice(5).map(([h, k]) => Number(k) ** 2 * Math.abs(PHI - Number(h) / Number(k)));
  const limit = 1 / Math.sqrt(5);
  eq('φ: q²|φ−p/q| → 1/√5 = 0.4472 (the Hurwitz floor)', tail[tail.length - 1], limit, 0.01);
}

console.log('\n=== IV.  One algorithm, three signatures ===\n');
// The unifying reading: the size of the continued-fraction terms measures how
// hard a number resists rational closure.
//   √2  → [1; 2,2,2,…]   steady resistance (periodic)
//   3/2 in the octave → [0;1,1,2,2,3,1,5,…]  growing terms = ever-better near-misses
//                                            (each big term is a temperament that nearly works)
//   φ   → [1; 1,1,1,…]   smallest terms possible = the maximal refusal
// The claim "φ is hardest" is precisely "φ's terms are minimal", and the claim
// "the comma is small" is precisely "log2(3/2) has a decent early convergent (7/12)".
{
  const meanTerm = (a) => a.reduce((s, x) => s + x, 0) / a.length;
  const phiTerms = [1, 1, 1, 1, 1, 1, 1, 1];
  const fifthTerms = [1, 1, 2, 2, 3, 1, 5];        // drop the leading 0
  eq('φ has the minimum possible mean term (=1)', meanTerm(phiTerms), 1, 0);
  eq('the fifth has larger terms than φ (more catchable)', meanTerm(fifthTerms) > 1, true);
  // A big term ⇒ a strong convergent just before it. The 5 in the fifth's CF is
  // why 31/53 (53-EDO) is so good; the all-1s in φ is why nothing is.
  eq('the fifth contains a term ≥ 3 (a near-closure); φ never does',
     Math.max(...fifthTerms) >= 3 && Math.max(...phiTerms) === 1, true);
}

console.log(`\n${'='.repeat(56)}\n${pass} passed, ${fail} failed\n`);
process.exit(fail ? 1 : 0);
