// verify.mjs — offline verifier for the immersive stratum "What is e?"
// Recomputes every number the page asserts, in exact integer/rational
// arithmetic (BigInt) wherever the quantity is rational, and to full double
// precision where it is the transcendental limit. No claim on the page is
// allowed that does not pass here.
//   node research/eulers-number/verify.mjs
//
// Facts checked:
//   (1) e to 15 places.
//   (2) (1+1/n)^n climbs toward e from BELOW and never reaches it at finite n;
//       the gap is ~ e/(2n) to leading order (compound-interest origin).
//   (3) The factorial series Σ 1/k! converges to e, far faster than compounding;
//       partial sums shown as EXACT rationals (BigInt).
//   (4) Derangements D_n = n·D_{n-1} + (-1)^n (exact integers); D_n/n! → 1/e,
//       so the hat-check probability that NOBODY gets their own hat → 1/e.
//   (5) The slope of b^x at x=0 is ln(b); it equals 1 (the function is its own
//       derivative) exactly at b=e — the property that singles e out.
//   (6) Euler's continued fraction e = [2; 1,2,1,1,4,1,1,6,1,1,8,…] converges to e
//       (its non-termination is one proof e is irrational; Euler, 1737).

const E = Math.E; // 2.718281828459045 — the IEEE-754 double nearest e
let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};
const near = (a, b, tol) => Math.abs(a - b) <= tol;

console.log('— (1) the constant —');
ok('e = 2.718281828459045', E.toFixed(15) === '2.718281828459045', E.toFixed(15));

console.log('\n— (2) compounding: (1+1/n)^n → e from below, gap ~ e/2n —');
// Use exp(n·log1p(1/n)): exact pow overshoots e at large n from float error.
const compound = (n) => Math.exp(n * Math.log1p(1 / n));
const presets = [
  [1, 2.0], [2, 2.25], [4, 2.44140625], [12, 2.61303529], [52, 2.69259695],
  [365, 2.71456748], [8760, 2.71812669], [525600, 2.71827924], [31536000, 2.71828178],
];
let prev = 0;
for (const [n, want] of presets) {
  const v = compound(n);
  ok(`n=${n}: (1+1/n)^n ≈ ${want}`, near(v, want, 5e-8), v.toFixed(8));
  ok(`n=${n}: strictly below e`, v < E, `gap=${(E - v).toExponential(3)}`);
  ok(`n=${n}: monotone increasing in n`, v > prev);
  prev = v;
}
// leading-order rate: e − (1+1/n)^n ≈ e/(2n). Check the ratio → 1 as n grows.
for (const n of [365, 8760, 525600]) {
  const ratio = (E - compound(n)) / (E / (2 * n));
  ok(`n=${n}: gap/(e/2n) ≈ 1`, near(ratio, 1, 0.01), ratio.toFixed(5));
}

console.log('\n— (3) the factorial series Σ1/k! (exact rationals) → e —');
// Track the partial sum as an exact fraction num/den with den = k! (BigInt).
let num = 0n, den = 1n; // 0/1
const fact = (k) => { let f = 1n; for (let i = 2n; i <= BigInt(k); i++) f *= i; return f; };
const wantSums = ['1', '2', '2.5', '2.666667', '2.708333', '2.716667', '2.718056', '2.718254', '2.718279'];
let lastErr = Infinity;
for (let k = 0; k <= 8; k++) {
  const fk = fact(k);
  // add 1/k!: num/den + 1/fk  with den always = current k! → just rescale to fk
  num = num * (fk / den) + 1n; den = fk; // since den divides fk
  const dec = Number(num) / Number(den);
  ok(`Σ_{0..${k}} 1/k! = ${num}/${den} ≈ ${wantSums[k]}`, dec.toFixed(6).startsWith(wantSums[k].slice(0, 6)) || near(dec, parseFloat(wantSums[k]), 5e-7), dec.toFixed(6));
  const err = Math.abs(E - dec);
  ok(`  term ${k}: error shrinks`, k === 0 || err < lastErr, `err=${err.toExponential(3)}`);
  lastErr = err;
}
ok('series reaches e faster than compounding at n=8 vs n=8760',
   Math.abs(E - Number(num) / Number(den)) < Math.abs(E - compound(8760)),
   `series err=${(E - Number(num) / Number(den)).toExponential(2)} < compound(8760) err=${(E - compound(8760)).toExponential(2)}`);

console.log('\n— (4) derangements: D_n exact; D_n/n! → 1/e —');
// D_0 = 1; D_n = n·D_{n-1} + (-1)^n  (all exact, BigInt)
const wantD = ['1', '0', '1', '2', '9', '44', '265', '1854', '14833'];
let D = 1n; const Darr = [1n];
for (let n = 1; n <= 8; n++) { D = BigInt(n) * D + (n % 2 === 0 ? 1n : -1n); Darr.push(D); }
ok('D_n sequence = 1,0,1,2,9,44,265,1854,14833 (OEIS A000166)',
   Darr.map(String).join(',') === wantD.join(','), Darr.map(String).join(','));
let fn = 1n;
for (let n = 1; n <= 8; n++) {
  fn = fn * BigInt(n);
  const r = Number(Darr[n]) / Number(fn);
  ok(`P(no fixed point), n=${n}: D_n/n! = ${Darr[n]}/${fn} = ${r.toFixed(6)}`, true, `1/e=${(1 / E).toFixed(6)}`);
}
const r8 = Number(Darr[8]) / Number(fn);
ok('by n=8, D_n/n! within 3e-6 of 1/e', near(r8, 1 / E, 3e-6), `|Δ|=${Math.abs(r8 - 1 / E).toExponential(2)}`);

console.log('\n— (5) e is the base that is its own derivative —');
// slope of b^x at x=0 = ln(b); = 1 iff b=e
for (const b of [2, 2.5, 3]) ok(`base ${b}: slope at 0 = ln(${b}) ≠ 1`, Math.abs(Math.log(b) - 1) > 1e-3, Math.log(b).toFixed(6));
ok('base e: slope at 0 = ln(e) = 1 (own derivative)', near(Math.log(E), 1, 1e-12), Math.log(E).toFixed(12));
// numerical derivative of e^x at x=0 should also be ≈ 1
const h = 1e-6;
ok('numerical d/dx e^x at 0 ≈ 1', near((Math.exp(h) - Math.exp(-h)) / (2 * h), 1, 1e-9));

console.log('\n— (6) Euler\'s continued fraction e = [2;1,2,1,1,4,1,1,6,…] —');
const cf = [2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10, 1, 1, 12];
let val = cf[cf.length - 1];
for (let i = cf.length - 2; i >= 0; i--) val = cf[i] + 1 / val;
ok('CF [2;1,2,1,1,4,1,1,6,…] converges to e', near(val, E, 1e-10), val.toFixed(12));

console.log('\n— (7) the digit coincidence is real, and only a coincidence —');
const digits = '2.718281828459045235360287'; // first 25 sig digits
ok('"1828" appears twice running (after the 2.7)', digits.slice(3).startsWith('1828' + '1828'), digits);

console.log(`\n${fails === 0 ? 'ALL PASS' : fails + ' FAILED'}`);
process.exit(fails === 0 ? 0 : 1);
