#!/usr/bin/env node
// ─────────────────────────────────────────────────────────────────────────────
// verify.mjs — The Fast Inverse Square Root, checked from the bits up.
//
// The famous Quake III `Q_rsqrt`:
//
//     i  = * ( long * ) &y;                       // evil floating point bit level hacking
//     i  = 0x5f3759df - ( i >> 1 );               // what the fuck?
//     y  = * ( float * ) &i;
//     y  = y * ( 1.5f - ( 0.5f*x * y * y ) );     // 1st Newton iteration
//
// Every claim the stratum makes is recomputed here in single-precision (Math.fround),
// reproducing the exact IEEE-754 float32 arithmetic the C code runs. Run: `node verify.mjs`.
// ─────────────────────────────────────────────────────────────────────────────

const fr = Math.fround;

// The one honest way to reinterpret a float32's bits as an integer and back in JS:
// alias the same 4 bytes as both a Float32 and a Uint32.
const _buf = new ArrayBuffer(4);
const _f32 = new Float32Array(_buf);
const _u32 = new Uint32Array(_buf);
const floatToBits = (x) => { _f32[0] = x; return _u32[0]; };       // the `*(long*)&y`
const bitsToFloat = (i) => { _u32[0] = i >>> 0; return _f32[0]; }; // the `*(float*)&i`

const QUAKE = 0x5f3759df;          // the magic constant, verbatim from q_math.c
const LOMONT_SEARCH   = 0x5f375a86; // Lomont 2003, found by exhaustive search (min max-err after 1 NR)
const LOMONT_ANALYTIC = 0x5f37642f; // Lomont 2003, derived in closed form (a different optimum)

// The algorithm, faithful to the C: bit-hack seed + `iters` Newton–Raphson steps, all in float32.
function fastInvSqrt(x, R = QUAKE, iters = 1) {
  let i = floatToBits(fr(x));
  i = (R - (i >>> 1)) >>> 0;         // subtract half the bit-pattern from the magic constant
  let y = bitsToFloat(i);
  const halfx = fr(0.5 * fr(x));
  for (let k = 0; k < iters; k++) y = fr(y * fr(1.5 - fr(halfx * fr(y * y))));
  return y;
}

// Max relative error of the estimator over a geometric sweep of x in [lo, hi].
function maxRelErr(R, iters, lo = 0.25, hi = 4, N = 400000) {
  let mx = 0, at = lo;
  for (let k = 0; k <= N; k++) {
    const x = lo * Math.pow(hi / lo, k / N);
    const e = Math.abs(fastInvSqrt(x, R, iters) - 1 / Math.sqrt(x)) / (1 / Math.sqrt(x));
    if (e > mx) { mx = e; at = x; }
  }
  return { mx, at };
}

// ── harness ──────────────────────────────────────────────────────────────────
let pass = 0, fail = 0;
const ok = (name, cond, detail = '') => {
  (cond ? (pass++, console.log(`  ok   ${name}${detail ? ' — ' + detail : ''}`))
        : (fail++, console.log(`  FAIL ${name}${detail ? ' — ' + detail : ''}`)));
};
const approx = (a, b, tol) => Math.abs(a - b) <= tol;

console.log('\nThe Fast Inverse Square Root — verification\n');

// 1. Bit reinterpretation round-trips exactly (the aliasing is honest).
{
  let clean = true;
  for (const x of [1, 2, 0.5, 3.14159, 0.15625, 1e-8, 1e8, 12345.678]) {
    if (bitsToFloat(floatToBits(fr(x))) !== fr(x)) clean = false;
  }
  ok('bit reinterpretation round-trips (float32 → uint32 → float32)', clean);
}

// 2. The magic constant and the log-approximation offset σ it encodes.
//    R = 1.5 · 2^23 · (127 − σ)  ⇒  σ = 127 − R / (1.5·2^23).
{
  ok('QUAKE constant = 0x5f3759df = 1597463007', QUAKE === 1597463007, String(QUAKE));
  const sigma = 127 - QUAKE / (1.5 * 2 ** 23);
  ok('implied log-correction σ ≈ 0.0450466', approx(sigma, 0.0450466, 1e-6), `σ = ${sigma.toFixed(7)}`);
}

// 3. "The bits ARE a logarithm." Reading the bit pattern as an integer and scaling gives
//    I/2^23 − 127 ≈ log2(x). Verify the raw approximation and the σ-centred one.
{
  let rawMax = 0, ctrMax = 0;
  const sigma = 0.0430; // the max-|error|-minimising shift (≈ half the raw span); distinct from the constant's σ
  for (let k = 0; k <= 200000; k++) {
    const x = 0.25 * Math.pow(16, k / 200000);        // [0.25, 4]
    const raw = floatToBits(fr(x)) / 2 ** 23 - 127;    // I/2^23 − 127
    rawMax = Math.max(rawMax, Math.abs(raw - Math.log2(x)));
    ctrMax = Math.max(ctrMax, Math.abs(raw + sigma - Math.log2(x)));
  }
  ok('I/2^23 − 127 tracks log2(x) to < 0.087 (raw)', rawMax < 0.087, `max |err| = ${rawMax.toFixed(5)}`);
  ok('…and to < 0.044 once centred by σ ≈ 0.043', ctrMax < 0.044, `max |err| = ${ctrMax.toFixed(5)}`);
}

// 4. The integer subtraction `R − (i>>1)` is exactly `−½·log2(x)` in that bit-as-log picture,
//    so the resulting float is a first-cut 1/√x. Its max relative error (no Newton) ≈ 3.44%.
{
  const { mx, at } = maxRelErr(QUAKE, 0, 0.25, 4);
  ok('raw bit-hack seed: max rel err ≈ 3.44%', approx(mx, 0.0344, 5e-4), `${(mx * 100).toFixed(4)}% at x=${at.toFixed(4)}`);
}

// 5. One Newton–Raphson step drives it to ≈ 0.175%; two steps to ≈ 0.0005%.
{
  const one = maxRelErr(QUAKE, 1, 0.25, 4);
  const two = maxRelErr(QUAKE, 2, 0.25, 4);
  ok('after 1 Newton step: max rel err ≈ 0.175%', approx(one.mx, 0.00175, 5e-5), `${(one.mx * 100).toFixed(5)}%`);
  ok('after 2 Newton steps: max rel err < 0.001%', two.mx < 1e-5, `${(two.mx * 100).toFixed(6)}%`);
}

// 6. The Newton line `y·(1.5 − 0.5·x·y²)` IS one iteration of Newton–Raphson on f(y)=y⁻²−x.
//    Newton: y ← y − f(y)/f'(y), f'(y) = −2y⁻³  ⇒  y ← y·(3/2 − (x/2)·y²). Compare, in doubles.
{
  let clean = true;
  for (const x of [0.3, 1, 2, 7.7, 100]) {
    for (const y of [0.1, 0.5, 1.3, 3]) {
      const quake = y * (1.5 - 0.5 * x * y * y);
      const newton = y - (Math.pow(y, -2) - x) / (-2 * Math.pow(y, -3));
      if (!approx(quake, newton, 1e-12)) clean = false;
    }
  }
  ok('the "1.5 − 0.5·x·y·y" line = one Newton–Raphson step on 1/y²−x', clean);
}

// 7. Constant comparison (after 1 NR step). Lomont's SEARCH constant is marginally better than
//    Quake's; his ANALYTIC constant is honestly NOT better on the min-max metric — report both.
{
  const q = maxRelErr(QUAKE, 1).mx;
  const s = maxRelErr(LOMONT_SEARCH, 1).mx;
  const a = maxRelErr(LOMONT_ANALYTIC, 1).mx;
  ok('Lomont search 0x5f375a86 beats Quake (marginally)', s < q,
     `${(s * 100).toFixed(5)}% < ${(q * 100).toFixed(5)}%`);
  ok('Lomont analytic 0x5f37642f is NOT better (min-max)', a > q,
     `${(a * 100).toFixed(5)}% > ${(q * 100).toFixed(5)}% — honest: the closed-form optimum ≠ the min-max optimum`);
}

// 8. Periodicity: the RELATIVE error repeats every factor of 4 in x (>>1 halves the exponent),
//    so a single [1,4) window characterises the whole positive range. err(x) ≈ err(4x).
{
  let mxDiff = 0;
  for (let k = 0; k <= 5000; k++) {
    const x = 1 + 3 * k / 5000;                 // x in [1,4]
    const e1 = (fastInvSqrt(x, QUAKE, 1) - 1 / Math.sqrt(x)) * Math.sqrt(x);
    const e2 = (fastInvSqrt(4 * x, QUAKE, 1) - 1 / Math.sqrt(4 * x)) * Math.sqrt(4 * x);
    mxDiff = Math.max(mxDiff, Math.abs(e1 - e2));
  }
  ok('relative error is periodic over ×4 in x (err(x) ≈ err(4x))', mxDiff < 1e-6, `max diff = ${mxDiff.toExponential(2)}`);
}

// 9. A concrete worked example the page can walk step-by-step (all recomputed, nothing hardcoded).
{
  const x = 0.15625;                             // = 5/32, a tidy example
  const i0 = floatToBits(fr(x));
  const i1 = (QUAKE - (i0 >>> 1)) >>> 0;
  const y0 = bitsToFloat(i1);
  const y1 = fastInvSqrt(x, QUAKE, 1);
  const truth = 1 / Math.sqrt(x);                // = 2.52982…
  console.log(`\n  worked example  x = ${x}:`);
  console.log(`    i  = 0x${i0.toString(16).padStart(8, '0')}  (${i0})`);
  console.log(`    i  = 0x5f3759df - (i>>1) = 0x${i1.toString(16).padStart(8, '0')}  (${i1})`);
  console.log(`    y0 (seed)      = ${y0.toFixed(6)}   err ${((y0 / truth - 1) * 100).toFixed(3)}%`);
  console.log(`    y1 (1 Newton)  = ${y1.toFixed(6)}   err ${((y1 / truth - 1) * 100).toFixed(4)}%`);
  console.log(`    true 1/√x      = ${truth}`);
  ok('worked example x=0.15625 → 1 Newton step within 0.2% of true 1/√x', Math.abs(y1 - truth) / truth < 0.002);
}

console.log(`\n${fail === 0 ? '✓' : '✗'} ${pass}/${pass + fail} checks green${fail ? ` (${fail} FAILED)` : ''}\n`);
process.exit(fail === 0 ? 0 : 1);
