Repository navigation
Expand file tree
/
Copy pathengine-diff.js
More file actions
874 lines (783 loc) · 40.3 KB
/
Copy pathengine-diff.js
File metadata and controls
874 lines (783 loc) · 40.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
/* ====================================================================
ENGINE — Numerical differentiation (Sheet 08)
----------------------------------------------------------------------
Five classic finite-difference formulas, exactly as specified:
1st derivative: Forward (f(x₀+h) − f(x₀)) / h O(h)
Backward (f(x₀) − f(x₀−h)) / h O(h)
Central (f(x₀+h) − f(x₀−h)) / 2h O(h²)
2nd derivative: Forward (f(x₀+2h) − 2f(x₀+h) + f(x₀)) / h² O(h)
Backward (f(x₀) − 2f(x₀−h) + f(x₀−2h)) / h² O(h)
The five formulas ARE the five steps: the graph highlights which
sample points each formula touches, draws its secant chord (1st
order) or interpolating parabola (2nd order), and overlays the TRUE
tangent line obtained from math.js symbolic differentiation — the
same trick Newton-Raphson uses — so exact absolute/relative errors
come for free. The table compares all five side by side.
Requires core.js loaded first. Follows the shared engine contract:
merge into NAW.METHODS, subscribe to NAW.onMethodChange(), guard
every shared-button handler with isActive(), and restore any shared
page chrome this sheet hid when it stops being active — the four
original sheets behave identically whether or not this file loads.
==================================================================== */
(function () {
'use strict';
const NAW = window.NAW;
const {
$, D, compileFn, parseVal, fmt, fmtE,
escHtml, showStatus, clearStatus,
dl, ts, canvasBlob, mkCaptureOverlay, waitFrames,
} = NAW;
/* ================================================================
SHARED PAGE CHROME this engine temporarily reconfigures while
its own sheet is active (restored verbatim on leave).
================================================================ */
const CHROME = {
fxField: $('fx-field'), // f(x) input row (kept — differentiation needs f!)
matrixWrap: $('matrix-fieldset'), // matrix textarea (belongs to Sheet 07)
aField: $('a-field'), // reused as x₀ (kept, relabeled via shapeCopy)
trueRootFld: $('true-root-field'), // true root (hidden — f′ is computed symbolically)
bracketFld: $('bracket-fieldset'), // bracket auto/manual (hidden — no brackets here)
stopFld: $('stop-fieldset'), // stop-after criteria (hidden — fixed 5 formulas)
hWrap: $('h-field-wrap'), // step size h (shown — this sheet's extra input)
};
function applySheetChrome() {
if (CHROME.fxField) CHROME.fxField.hidden = false;
if (CHROME.matrixWrap) CHROME.matrixWrap.hidden = true;
if (CHROME.aField) CHROME.aField.hidden = false;
if (CHROME.trueRootFld) CHROME.trueRootFld.hidden = true;
if (CHROME.bracketFld) CHROME.bracketFld.hidden = true;
if (CHROME.stopFld) CHROME.stopFld.hidden = true;
if (CHROME.hWrap) CHROME.hWrap.hidden = false;
/* x₀ lives in the shared a-input — enable it no matter what the
(now hidden) bracket-mode radio says */
if (D.aInput) {
D.aInput.disabled = false;
D.aInput.placeholder = 'e.g. pi/4 or 0.5';
}
}
function restoreChrome() {
if (CHROME.fxField) CHROME.fxField.hidden = false;
if (CHROME.matrixWrap) CHROME.matrixWrap.hidden = true;
if (CHROME.aField) CHROME.aField.hidden = false;
if (CHROME.trueRootFld) CHROME.trueRootFld.hidden = false;
if (CHROME.bracketFld) CHROME.bracketFld.hidden = false;
if (CHROME.stopFld) CHROME.stopFld.hidden = false;
if (CHROME.hWrap) CHROME.hWrap.hidden = true;
/* put the a/b inputs back exactly the way the bracketing engine's
own radio-change handler leaves them for the current mode */
const modeEl = document.querySelector('[name="bracketMode"]:checked');
const manual = modeEl ? modeEl.value === 'manual' : false;
if (D.aInput) {
D.aInput.disabled = !manual;
D.aInput.placeholder = manual ? 'e.g. 1 or pi/2' : 'auto-detected on Solve';
if (!manual) D.aInput.value = '';
}
if (D.bInput) {
D.bInput.disabled = !manual;
D.bInput.placeholder = manual ? 'e.g. 2 or e' : 'auto-detected on Solve';
if (!manual) D.bInput.value = '';
}
}
/* ================================================================
STATE
================================================================ */
let _res = []; // one result object per formula
let _idx = 0;
let _playTmr = null;
let _heroTmr = null;
let _fn = null;
let _d1 = null; // compiled f′ (symbolic)
let _d2 = null; // compiled f″ (symbolic)
let _d1Expr = '';
let _d2Expr = '';
let _x0 = NaN;
let _h = NaN;
let _bestIdx = -1;
let _exIdx = 0;
const isActive = () => (NAW.getActiveMethod() in METHODS);
/* ================================================================
EXAMPLES
================================================================ */
const EXAMPLES = [
{ fx: 'sin(x)', x0: 'pi/4', h: '0.1', note: 'sin at π/4 — central difference visibly beats forward/backward' },
{ fx: 'exp(x)', x0: '1', h: '0.01', note: 'eˣ with tiny h — all five land on e ≈ 2.71828' },
{ fx: 'x^3 - 4*x', x0: '2', h: '0.5', note: 'Cubic, big h — watch the truncation error in every column' },
{ fx: 'ln(x)', x0: '2', h: '0.25', note: 'Natural log at 2 — f′ = 0.5 exactly' },
{ fx: 'cos(x)', x0: '0', h: '0.25', note: 'cos at 0 — f′ = 0, f″ = −1' },
{ fx: 'e^x - x^2', x0: '0.5', h: '0.05', note: 'Mixed exponential-polynomial' },
];
/* ================================================================
THE FIVE FORMULAS — data-driven so table/graph/export/GIF all
read from this one list. deriv: 1 or 2 (which exact derivative
to compare against).
================================================================ */
const FORMULAS = [
{
key: 'fwd1', name: 'Forward difference — 1st derivative', short: 'Forward 1st',
order: 'O(h)', deriv: 1,
formula: 'f′(x₀) ≈ (f(x₀+h) − f(x₀)) / h',
val: (f, x, h) => (f(x + h) - f(x)) / h,
pts: (x, h) => [x, x + h],
labels: ['x₀', 'x₀+h'],
},
{
key: 'bwd1', name: 'Backward difference — 1st derivative', short: 'Backward 1st',
order: 'O(h)', deriv: 1,
formula: 'f′(x₀) ≈ (f(x₀) − f(x₀−h)) / h',
val: (f, x, h) => (f(x) - f(x - h)) / h,
pts: (x, h) => [x - h, x],
labels: ['x₀−h', 'x₀'],
},
{
key: 'cen1', name: 'Central difference — 1st derivative', short: 'Central 1st',
order: 'O(h²)', deriv: 1,
formula: 'f′(x₀) ≈ (f(x₀+h) − f(x₀−h)) / 2h',
val: (f, x, h) => (f(x + h) - f(x - h)) / (2 * h),
pts: (x, h) => [x - h, x + h],
labels: ['x₀−h', 'x₀+h'],
},
{
key: 'fwd2', name: 'Forward difference — 2nd derivative', short: 'Forward 2nd',
order: 'O(h)', deriv: 2,
formula: 'f″(x₀) ≈ (f(x₀+2h) − 2f(x₀+h) + f(x₀)) / h²',
val: (f, x, h) => (f(x + 2 * h) - 2 * f(x + h) + f(x)) / (h * h),
pts: (x, h) => [x, x + h, x + 2 * h],
labels: ['x₀', 'x₀+h', 'x₀+2h'],
},
{
key: 'bwd2', name: 'Backward difference — 2nd derivative', short: 'Backward 2nd',
order: 'O(h)', deriv: 2,
formula: 'f″(x₀) ≈ (f(x₀) − 2f(x₀−h) + f(x₀−2h)) / h²',
val: (f, x, h) => (f(x) - 2 * f(x - h) + f(x - 2 * h)) / (h * h),
pts: (x, h) => [x - 2 * h, x - h, x],
labels: ['x₀−2h', 'x₀−h', 'x₀'],
},
];
/* ================================================================
METHODS REGISTRY ENTRY
================================================================ */
const METHODS = {
numdiff: {
id: 'numdiff',
num: '08',
docTitle: 'Numerical Differentiation',
heroTitleHTML: 'Numerical differentiation,<br>five formulas, <span class="accent">one picture</span>.',
heroSub: 'Give it a function, a point x₀, and a step h. All five finite-difference formulas — forward, backward, and central for the 1st derivative, forward and backward for the 2nd — run at once, drawn against the true tangent from symbolic differentiation so you can see exactly which formula wins.',
metaMethod: 'Finite differences (forward · backward · central)',
metaOrder: 'O(h) — or O(h²) for the central 1st derivative',
metaNeeds: 'f(x), a point x₀, and a step h',
cLabel: 'approximation',
cColHeader: 'Approximation',
graphAria: 'Plot of f(x) highlighting the sample points each difference formula uses',
heroGraphAria: 'Animated demo cycling the five finite-difference formulas',
needsMsg: 'Differentiation needs a valid f(x), a finite x₀ and a nonzero step h.',
hideB: true,
shapeCopy: {
'a-input-label': 'x\u2080 (evaluation point)',
'read-a-label': 'x\u2080',
'read-b-label': 'h',
'read-fc-label': 'abs. error',
},
},
};
Object.assign(NAW.METHODS, METHODS);
/* ================================================================
SYMBOLIC DERIVATIVES — same approach as Newton-Raphson's engine:
math.js parses once, differentiates twice, and we compile both.
Returns null if the expression can't be differentiated (the five
approximations still work — only the exact-error columns drop out).
================================================================ */
function compileDerivatives(expr) {
try {
const processed = NAW.remapLogNotation(NAW.preprocessExpr(expr.trim()));
const node = math.parse(processed);
const d1n = math.derivative(node, 'x');
const d2n = math.derivative(d1n, 'x');
const mk = dn => {
const scope = {};
const fn = x => {
scope.x = x;
const r = dn.evaluate(scope);
return typeof r === 'number' ? r : NaN;
};
fn.text = dn.toString({ implicit: 'hide' });
return fn;
};
return { d1: mk(d1n), d2: mk(d2n) };
} catch { return null; }
}
/* ================================================================
SOLVE
================================================================ */
function solve(e) {
if (!isActive()) return;
e?.preventDefault();
clearStatus();
if (_playTmr) { clearInterval(_playTmr); _playTmr = null; D.playBtn.textContent = '▶'; }
/* --- f(x) --- */
const fxRaw = D.fxInput.value.trim();
if (!fxRaw) return showStatus('Enter a function f(x) first.');
if (fxRaw.length > 500) return showStatus('Expression is too long — please keep it under 500 characters.');
const fn = compileFn(fxRaw);
if (!fn) return showStatus(`Cannot parse "${escHtml(fxRaw)}". Check your syntax — expand the tutorial below.`);
/* --- symbolic f′ / f″ (optional luxury) --- */
const derivs = compileDerivatives(fxRaw);
_d1 = derivs ? derivs.d1 : null;
_d2 = derivs ? derivs.d2 : null;
_d1Expr = _d1 ? _d1.text : '';
_d2Expr = _d2 ? _d2.text : '';
/* --- x₀ (shared a-input) --- */
const x0Raw = D.aInput.value.trim();
if (!x0Raw) return showStatus('Enter an evaluation point x₀.');
if (x0Raw.length > 200) return showStatus('x₀ expression is too long (max 200 characters).');
const x0 = parseVal(x0Raw);
if (isNaN(x0)) return showStatus(`Cannot evaluate x₀ = "${escHtml(x0Raw)}". Use a number or an expression like pi/4, e, sqrt(2).`);
/* --- h --- */
const hRaw = $('h-input').value.trim();
if (!hRaw) return showStatus('Enter a step size h.');
if (hRaw.length > 200) return showStatus('Step expression is too long (max 200 characters).');
const h = parseVal(hRaw);
if (isNaN(h)) return showStatus(`Cannot evaluate h = "${escHtml(hRaw)}". Use a number or an expression like 0.1, pi/100.`);
if (!isFinite(h) || Math.abs(h) < 1e-12)
return showStatus('Step h must be nonzero (and not absurdly tiny — below 10⁻¹² everything melts into rounding noise).');
const f0 = fn(x0);
if (!isFinite(f0)) return showStatus(`f(${fmt(x0)}) is not finite — pick an x₀ where the function is defined.`);
/* --- run all five formulas --- */
const res = [];
let bestIdx = -1, bestAe = Infinity;
for (const F of FORMULAS) {
let val = NaN, ok = true;
for (const px of F.pts(x0, h))
if (!isFinite(fn(px))) { ok = false; break; }
if (ok) { val = F.val(fn, x0, h); ok = isFinite(val); }
let exact = null;
if (_d1 || _d2) {
const ex = (F.deriv === 1 ? _d1 : _d2)(x0);
if (isFinite(ex)) exact = ex;
}
const ae = (exact != null && ok) ? Math.abs(val - exact) : null;
const re = (ae != null && Math.abs(exact) > 1e-14) ? ae / Math.abs(exact) : null;
const r = { key: F.key, val: ok ? val : NaN, exact, ae, re, ok };
res.push(r);
if (ae != null && ae < bestAe) { bestAe = ae; bestIdx = res.length - 1; }
}
_fn = fn; _x0 = x0; _h = h;
_res = res; _bestIdx = bestIdx;
if (!_d1 && !_d2)
showStatus('Computed all five approximations — but f′/f″ could not be built symbolically for this expression, so the exact-error columns are unavailable.', 'error');
else if (res.some(r => !r.ok))
showStatus('Some formulas hit points where f is not defined — their rows show “—”. Try a smaller h or a different x₀.', 'error');
_idx = 0;
D.solSec.hidden = false;
D.vizSec.hidden = false;
D.tblSec.hidden = false;
renderSolBox();
renderTable();
renderGraph(0);
D.solSec.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
/* ================================================================
RENDER: SOLUTION BOX
================================================================ */
function renderSolBox() {
const last = _res[_bestIdx >= 0 ? _bestIdx : 0];
const bestF = _bestIdx >= 0 ? FORMULAS[_bestIdx] : null;
D.solBox.innerHTML = `
<div class="sol-group">
<div class="sol-lbl">Equation</div>
<div class="sol-eq">f(x) = ${escHtml(D.fxInput.value.trim())}</div>
</div>
<div class="sol-group">
<div class="sol-lbl">Setup</div>
<div class="bracket-box">
<div class="bc-row"><code>x\u2080 = ${fmt(_x0)}</code><span class="sign-pill pos">evaluation point</span></div>
<div class="bc-row"><code>h = ${fmt(_h)}</code><span class="sign-pill pos">step size</span></div>
<div class="bc-row"><code>f(x\u2080) = ${fmt(_fn(_x0))}</code></div>
<div class="bc-row ivt-row">
<code>f\u2032(x) = ${_d1 ? escHtml(_d1Expr) : 'unavailable'}</code>
<span class="ivt-note">\u2192 computed symbolically — no manual differentiation needed</span>
</div>
<div class="bc-row"><code>f\u2033(x) = ${_d2 ? escHtml(_d2Expr) : 'unavailable'}</code></div>
</div>
</div>
<div class="sol-group">
<div class="sol-lbl">Result — all five formulas at x\u2080 = ${fmt(_x0)}, h = ${fmt(_h)}</div>
<div class="result-row">
${bestF
? `<span class="root-chip">${escHtml(bestF.short)}: ${last.exact != null ? fmt(last.val) : fmt(last.val)}</span>`
: `<span class="root-chip">see table</span>`}
${bestF && last.ae != null ? `<span class="conv-chip">\u2713 most accurate — AE = ${fmtE(last.ae)}</span>` : ''}
${bestF ? `<span class="ae-note">${escHtml(bestF.formula)}</span>` : ''}
</div>
</div>
`;
}
/* ================================================================
RENDER: ITERATION TABLE — one row per formula
================================================================ */
function renderTable() {
D.tHead.innerHTML = ['Formula', 'Order', 'Approximation', 'Exact', 'AE', 'RE']
.map(h => `<th>${h}</th>`).join('');
D.capSum.textContent =
`f(x) = ${D.fxInput.value.trim()} · x\u2080 = ${fmt(_x0)} · h = ${fmt(_h)}` +
` · five finite-difference formulas${_bestIdx >= 0 ? ` · best: ${FORMULAS[_bestIdx].short}` : ''}`;
D.tblNote.textContent = _d1 && _d2
? `Exact column = symbolic f\u2032(x\u2080) or f\u2033(x\u2080); AE = |approx − exact|; RE = AE / |exact|. Central 1st is O(h²) — halving h cuts its error ×4, the others only ×2.`
: `Exact/error columns unavailable (no symbolic derivative) — approximations are still valid.`;
D.tBody.innerHTML = '';
FORMULAS.forEach((F, i) => {
const r = _res[i];
const tr = document.createElement('tr');
if (i === _idx) tr.classList.add('active-row');
if (i === _bestIdx) tr.classList.add('converged-row');
tr.innerHTML = [
`<td style="text-align:left;text-transform:none;">${escHtml(F.name)}</td>`,
`<td>${F.order}</td>`,
`<td class="c-val">${r.ok ? fmt(r.val) : '—'}</td>`,
`<td>${r.exact != null ? fmt(r.exact) : '—'}</td>`,
`<td>${r.ae != null ? fmtE(r.ae) : '—'}</td>`,
`<td>${r.re != null ? fmtE(r.re) : '—'}</td>`,
].join('');
D.tBody.appendChild(tr);
});
}
/* ================================================================
RENDER: MAIN GRAPH
Curve + the five sample points; the active formula's points glow
copper, its secant chord (1st order) or interpolating parabola
(2nd order) is drawn dashed, and the TRUE tangent line from the
symbolic derivative runs underneath as the reference.
================================================================ */
function renderGraph(idx) {
const pal = NAW.graphPalette();
if (!_res.length || !_fn) return;
const F = FORMULAS[idx];
const r = _res[idx];
const W = 800, H = 456;
const pL = 72, pR = 24, pT = 30, pB = 82;
const pW = W - pL - pR, pH = H - pT - pB;
/* window: a few h-widths around x₀ (with a sane minimum) */
const half = Math.max(Math.abs(_h) * 3, Math.abs(_x0) * 1e-6 + 1e-9);
const xMin = _x0 - half, xMax = _x0 + half;
const N = 400;
const xs = Array.from({ length: N + 1 }, (_, i) => xMin + (xMax - xMin) * i / N);
const ys = xs.map(x => { const v = _fn(x); return isFinite(v) ? v : null; });
const valid = ys.filter(y => y != null);
if (!valid.length) return;
let yMin = Math.min(...valid), yMax = Math.max(...valid);
const yMg = (yMax - yMin) * 0.14 || 1;
yMin -= yMg; yMax += yMg;
const tx = x => pL + (x - xMin) / (xMax - xMin) * pW;
const ty = y => pT + (1 - (y - yMin) / (yMax - yMin)) * pH;
const clampY = y => Math.max(pT, Math.min(pT + pH, y));
let path = '', pen = false;
for (let i = 0; i <= N; i++) {
if (ys[i] == null) { pen = false; continue; }
const px = tx(xs[i]).toFixed(1), py = ty(ys[i]).toFixed(1);
path += pen ? ` L${px} ${py}` : `M${px} ${py}`;
pen = true;
}
const xAY = ty(0), yAX = tx(0);
let svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${W} ${H}">`;
for (let i = 0; i <= 8; i++) {
const gx = (pL + i * pW / 8).toFixed(1);
svg += `<line x1="${gx}" y1="${pT}" x2="${gx}" y2="${pT + pH}" stroke="rgba(${pal.gridRGB},.15)" stroke-width="1"/>`;
}
for (let i = 0; i <= 6; i++) {
const gy = (pT + i * pH / 6).toFixed(1);
svg += `<line x1="${pL}" y1="${gy}" x2="${pL + pW}" y2="${gy}" stroke="rgba(${pal.gridRGB},.15)" stroke-width="1"/>`;
}
if (xAY > pT && xAY < pT + pH)
svg += `<line x1="${pL}" y1="${xAY.toFixed(1)}" x2="${pL + pW}" y2="${xAY.toFixed(1)}" stroke="${pal.axis}" stroke-width="1.5"/>`;
if (yAX > pL && yAX < pL + pW)
svg += `<line x1="${yAX.toFixed(1)}" y1="${pT}" x2="${yAX.toFixed(1)}" y2="${pT + pH}" stroke="${pal.axis}" stroke-width="1.5"/>`;
for (let i = 0; i <= 8; i++) {
const xv = xMin + (xMax - xMin) * i / 8;
const xp = (pL + i * pW / 8).toFixed(1);
svg += `<text x="${xp}" y="${pT + pH + 16}" text-anchor="middle" font-size="10" fill="${pal.tick}" font-family="IBM Plex Mono,monospace">${xv.toFixed(3)}</text>`;
svg += `<line x1="${xp}" y1="${pT + pH}" x2="${xp}" y2="${pT + pH + 5}" stroke="${pal.tickLine}" stroke-width="1"/>`;
}
for (let i = 0; i <= 6; i++) {
const yv = yMin + (yMax - yMin) * (1 - i / 6);
const yp = (pT + i * pH / 6).toFixed(1);
svg += `<text x="${pL - 7}" y="${+yp + 3}" text-anchor="end" font-size="10" fill="${pal.tick}" font-family="IBM Plex Mono,monospace">${yv.toFixed(3)}</text>`;
svg += `<line x1="${pL - 4}" y1="${yp}" x2="${pL}" y2="${yp}" stroke="${pal.tickLine}" stroke-width="1"/>`;
}
svg += `<text x="${(pL + pW / 2).toFixed(0)}" y="${H - 60}" text-anchor="middle" font-size="11" fill="${pal.axis}" font-family="IBM Plex Sans Condensed,sans-serif">x</text>`;
svg += `<text x="13" y="${(pT + pH / 2).toFixed(0)}" text-anchor="middle" font-size="11" fill="${pal.axis}" font-family="IBM Plex Sans Condensed,sans-serif" transform="rotate(-90 13 ${(pT + pH / 2).toFixed(0)})">f(x)</text>`;
/* TRUE tangent line at x₀ — the ground truth every formula chases */
if (_d1) {
const m = _d1(_x0), b0 = _fn(_x0) - m * _x0;
if (isFinite(m)) {
const y1 = clampY(ty(m * xMin + b0)), y2 = clampY(ty(m * xMax + b0));
svg += `<line x1="${tx(xMin).toFixed(1)}" y1="${y1.toFixed(1)}" x2="${tx(xMax).toFixed(1)}" y2="${y2.toFixed(1)}" stroke="${pal.curve}" stroke-width="1.4" opacity="0.55"/>`;
svg += `<text x="${(pL + pW - 8).toFixed(1)}" y="${(clampY(ty(m * (xMax - 0.02 * (xMax - xMin)) + b0)) - 6).toFixed(1)}" text-anchor="end" font-size="10" fill="${pal.curve}" font-family="IBM Plex Mono,monospace" opacity="0.8">true slope = ${isFinite(m) ? fmt(m) : '?'}</text>`;
}
}
/* the active formula's own construction */
const P = F.pts(_x0, _h);
const fP = P.map(px => _fn(px));
if (F.deriv === 1 && fP.every(isFinite)) {
/* secant chord through the two points, extended across the plot */
const m = (fP[1] - fP[0]) / (P[1] - P[0]);
const b0 = fP[0] - m * P[0];
const y1 = clampY(ty(m * xMin + b0)), y2 = clampY(ty(m * xMax + b0));
svg += `<line x1="${tx(xMin).toFixed(1)}" y1="${y1.toFixed(1)}" x2="${tx(xMax).toFixed(1)}" y2="${y2.toFixed(1)}" stroke="${pal.c}" stroke-width="1.8" stroke-dasharray="6 3" opacity="0.9"/>`;
} else if (F.deriv === 2 && fP.every(isFinite)) {
/* interpolating parabola through the three points (Lagrange) */
const [xa, xb, xc] = P, [ya, yb, yc] = fP;
const q = t =>
ya * (t - xb) * (t - xc) / ((xa - xb) * (xa - xc)) +
yb * (t - xa) * (t - xc) / ((xb - xa) * (xb - xc)) +
yc * (t - xa) * (t - xb) / ((xc - xa) * (xc - xb));
let pp = '', pn = false;
for (let i = 0; i <= 80; i++) {
const t = xMin + (xMax - xMin) * i / 80;
const yv = q(t);
if (!isFinite(yv)) { pn = false; continue; }
const py = clampY(ty(yv)).toFixed(1);
pp += pn ? ` L${tx(t).toFixed(1)} ${py}` : `M${tx(t).toFixed(1)} ${py}`;
pn = true;
}
svg += `<path d="${pp}" fill="none" stroke="${pal.c}" stroke-width="1.8" stroke-dasharray="6 3" opacity="0.9"/>`;
}
/* curve above the lines */
svg += `<path d="${path}" fill="none" stroke="${pal.curve}" stroke-width="2.5" stroke-linejoin="round" stroke-linecap="round"/>`;
/* the five sample points — active formula's glow copper */
const allPts = [[_x0, 'x\u2080'], [_x0 + _h, '+h'], [_x0 - _h, '\u2212h'], [_x0 + 2 * _h, '+2h'], [_x0 - 2 * _h, '\u22122h']];
const actSet = new Set(P.map(v => v.toFixed(12)));
for (const [px0, lbl] of allPts) {
const yv = _fn(px0);
if (!isFinite(yv)) continue;
const isActivePt = actSet.has(px0.toFixed(12));
const col = isActivePt ? pal.c : pal.curve;
const rr = isActivePt ? 6 : 4;
const axY = clampY(ty(0)).toFixed(1);
const px = tx(px0).toFixed(1), py = ty(yv).toFixed(1);
if (isActivePt)
svg += `<line x1="${px}" y1="${py}" x2="${px}" y2="${axY}" stroke="${col}" stroke-width="1" stroke-dasharray="3 3" opacity="0.45"/>`;
svg += `<circle cx="${px}" cy="${py}" r="${rr}" fill="${col}" stroke="${pal.bgDeep}" stroke-width="1.5" ${isActivePt ? '' : 'opacity="0.45"'}/>`;
if (isActivePt)
svg += `<text x="${px}" y="${+py - rr - 5}" text-anchor="middle" font-size="11" fill="${col}" font-family="IBM Plex Mono,monospace" font-weight="500">${lbl}</text>`;
}
/* step overlay bar */
svg += `<rect x="${pL + 6}" y="${pT + 6}" width="430" height="20" rx="2" fill="rgba(${pal.bgDeepRGB},.75)"/>`;
svg += `<text x="${pL + 13}" y="${pT + 20}" font-size="11" fill="${pal.axis}" font-family="IBM Plex Mono,monospace">` +
`Formula ${idx + 1}/5 · ${escHtml(F.short)} · \u2248 ${r.ok ? fmt(r.val) : '—'}` +
`${r.ae != null ? ` · AE = ${fmtE(r.ae)}` : ''}</text>`;
svg += '</svg>';
D.bisGr.innerHTML = svg;
/* readings */
D.readA.textContent = fmt(_x0);
D.readB.textContent = fmt(_h);
D.readC.textContent = r.ok ? fmt(r.val) : '—';
D.readFc.textContent = r.ae != null ? fmtE(r.ae) : '—';
if (idx === FORMULAS.length - 1 && _bestIdx >= 0) {
D.readConvW.hidden = false;
D.readConv.textContent = `most accurate: ${FORMULAS[_bestIdx].short}`;
} else {
D.readConvW.hidden = true;
}
D.stepInd.textContent = `Formula ${idx + 1} of ${FORMULAS.length}`;
D.prevBtn.disabled = (idx === 0);
D.nextBtn.disabled = (idx >= FORMULAS.length - 1);
Array.from(D.tBody.querySelectorAll('tr')).forEach((row, i) => {
row.classList.toggle('active-row', i === idx);
});
}
/* ================================================================
PLAYBACK
================================================================ */
function goTo(idx) {
if (!isActive() || !_res.length) return;
_idx = Math.max(0, Math.min(idx, FORMULAS.length - 1));
renderGraph(_idx);
}
function togglePlay() {
if (!isActive() || !_res.length) return;
if (_playTmr) {
clearInterval(_playTmr); _playTmr = null;
D.playBtn.textContent = '▶';
D.playBtn.setAttribute('aria-label', 'Play');
} else {
if (_idx >= FORMULAS.length - 1) _idx = -1;
D.playBtn.textContent = '⏸';
D.playBtn.setAttribute('aria-label', 'Pause');
_playTmr = setInterval(() => {
_idx++;
if (_idx >= FORMULAS.length) {
clearInterval(_playTmr); _playTmr = null;
D.playBtn.textContent = '▶';
D.playBtn.setAttribute('aria-label', 'Play');
return;
}
renderGraph(_idx);
}, +D.speedSel.value);
}
}
/* ================================================================
RESET / HIDE
================================================================ */
function hideResults() {
if (_playTmr) { clearInterval(_playTmr); _playTmr = null; D.playBtn.textContent = '▶'; }
clearStatus();
D.solSec.hidden = true;
D.vizSec.hidden = true;
D.tblSec.hidden = true;
_res = []; _idx = 0; _fn = null; _d1 = null; _d2 = null; _bestIdx = -1;
D.prevBtn.disabled = true;
D.nextBtn.disabled = true;
}
function reset() {
if (!isActive()) return;
hideResults();
D.fxInput.value = '';
D.aInput.value = '';
const hi = $('h-input');
if (hi) hi.value = '';
D.fxDot.className = 'validity-dot';
}
/* ================================================================
EXPORTS — same off-screen landscape pipeline as the other engines
================================================================ */
function buildExportEl() {
const date = new Date().toLocaleDateString(undefined, { year:'numeric', month:'short', day:'numeric' });
const thS = 'padding:6px 9px;text-align:left;font-size:10px;text-transform:uppercase;letter-spacing:.06em;color:#7B93B0;border-bottom:2px solid rgba(61,102,148,.5);white-space:nowrap;background:#0e2140';
const tdB = 'padding:5px 9px;border-bottom:1px solid rgba(61,102,148,.2);text-align:left;white-space:nowrap;font-size:12px';
let rows = '';
FORMULAS.forEach((F, i) => {
const r = _res[i];
const rowBg = i === _bestIdx ? 'background:rgba(127,166,140,.1)' : '';
rows += `<tr style="${rowBg}">
<td style="${tdB};color:#EDEAE0">${escHtml(F.name)}</td>
<td style="${tdB};color:#7B93B0">${F.order}</td>
<td style="${tdB};color:#E2945F;font-weight:600">${r.ok ? fmt(r.val) : '—'}</td>
<td style="${tdB}">${r.exact != null ? fmt(r.exact) : '—'}</td>
<td style="${tdB}">${r.ae != null ? fmtE(r.ae) : '—'}</td>
<td style="${tdB}">${r.re != null ? fmtE(r.re) : '—'}</td>
</tr>`;
});
const inner = `
<div style="padding:28px 36px 20px;font-family:sans-serif;color:#EDEAE0;font-size:13px;line-height:1.5">
<div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:18px;padding-bottom:14px;border-bottom:1px solid rgba(61,102,148,.45)">
<div>
<div style="font-size:10px;color:#7B93B0;letter-spacing:.1em;text-transform:uppercase;margin-bottom:5px">Numerical Analysis Workbench · Numerical Differentiation</div>
<div style="font-size:20px;font-weight:700;color:#EDEAE0;font-family:monospace">f(x) = ${escHtml(D.fxInput.value.trim())}</div>
</div>
<div style="font-size:11px;color:#7B93B0;text-align:right;flex-shrink:0;margin-left:24px;font-family:monospace">
${escHtml(date)}<br>
<span style="color:#E2945F;font-size:14px;font-weight:700">x\u2080 = ${fmt(_x0)} · h = ${fmt(_h)}</span><br>
${_bestIdx >= 0 ? `<span style="color:#7FA68C">✓ best: ${escHtml(FORMULAS[_bestIdx].short)}</span>` : ''}
</div>
</div>
<div style="background:#081729;border-radius:3px;padding:11px 16px;margin-bottom:14px;font-family:monospace;font-size:12px;display:flex;gap:24px;flex-wrap:wrap;align-items:center">
<span style="color:#7B93B0;font-size:10px;text-transform:uppercase;letter-spacing:.08em">Symbolic</span>
<span>f′(x) = ${_d1 ? escHtml(_d1Expr) : 'unavailable'}</span>
<span>f″(x) = ${_d2 ? escHtml(_d2Expr) : 'unavailable'}</span>
${_d1 ? `<span>f′(x\u2080) = ${fmt(_d1(_x0))}</span>` : ''}
${_d2 ? `<span>f″(x\u2080) = ${fmt(_d2(_x0))}</span>` : ''}
</div>
<table style="width:100%;border-collapse:collapse;font-family:monospace;font-size:12px">
<thead><tr>${['Formula','Order','Approximation','Exact','AE','RE'].map(h => `<th style="${thS}">${h}</th>`).join('')}</tr></thead>
<tbody>${rows}</tbody>
</table>
<div style="font-size:10px;color:#7B93B0;margin-top:7px;font-family:monospace">
Forward/backward 1st & both 2nd-order formulas are O(h); the central 1st derivative is O(h²) — error ∝ h², so halving h divides its error by four.
</div>
<div style="font-size:10px;color:#7B93B0;padding-top:10px;margin-top:10px;border-top:1px dashed rgba(61,102,148,.4);display:flex;justify-content:space-between;font-family:monospace">
<span>S.M. Mehedy Kawser · mehedy.netlify.app</span>
<span>Generated ${escHtml(date)}</span>
</div>
</div>`;
const wrap = document.createElement('div');
wrap.style.cssText = 'position:fixed;top:0;left:0;width:1120px;background:#173A60;z-index:99998;overflow:visible;pointer-events:none';
wrap.innerHTML = inner;
document.body.appendChild(wrap);
return wrap;
}
async function exportImage() {
if (!isActive() || !_res.length) return;
const btn = D.expImg;
btn.textContent = 'Capturing…'; btn.disabled = true;
const overlay = mkCaptureOverlay('Preparing Image…');
const exportEl = buildExportEl();
await waitFrames();
try {
const canvas = await html2canvas(exportEl, {
backgroundColor: '#173A60', scale: 2, logging: false, useCORS: true, allowTaint: true,
width: 1120, height: exportEl.scrollHeight, windowWidth: 1200, scrollX: 0, scrollY: 0
});
dl(await canvasBlob(canvas), `${NAW.getActiveMethod()}_${ts()}.png`);
} catch (err) { alert('Image export failed: ' + err.message); }
finally {
exportEl.remove(); overlay.remove();
btn.textContent = 'Download as image'; btn.disabled = false;
}
}
async function exportPDF() {
if (!isActive() || !_res.length) return;
const btn = D.expPdf;
btn.textContent = 'Generating…'; btn.disabled = true;
const overlay = mkCaptureOverlay('Preparing PDF…');
const exportEl = buildExportEl();
await waitFrames();
try {
const canvas = await html2canvas(exportEl, {
backgroundColor: '#173A60', scale: 2, logging: false, useCORS: true, allowTaint: true,
width: 1120, height: exportEl.scrollHeight, windowWidth: 1200, scrollX: 0, scrollY: 0
});
const { jsPDF } = window.jspdf;
const pdf = new jsPDF({ orientation: 'landscape', unit: 'pt', format: 'a4' });
const pgW = pdf.internal.pageSize.getWidth();
const pgH = pdf.internal.pageSize.getHeight();
const imgData = canvas.toDataURL('image/png');
const imgH = (canvas.height / canvas.width) * pgW;
if (imgH <= pgH) {
pdf.addImage(imgData, 'PNG', 0, 0, pgW, imgH);
} else {
let yOff = 0;
while (yOff < imgH) {
if (yOff > 0) pdf.addPage();
pdf.addImage(imgData, 'PNG', 0, -yOff, pgW, imgH);
yOff += pgH;
}
}
pdf.save(`${NAW.getActiveMethod()}_${ts()}.pdf`);
} catch (err) { alert('PDF export failed: ' + err.message); }
finally {
exportEl.remove(); overlay.remove();
btn.textContent = 'Download as PDF'; btn.disabled = false;
}
}
function exportGIF() {
if (!isActive() || !_res.length) return;
NAW.exportGraphGIF({
svgEl: D.bisGr,
totalSteps: FORMULAS.length,
gotoStep: goTo,
currentIdx: _idx,
filename: `${NAW.getActiveMethod()}_${ts()}.gif`,
button: D.expGif,
});
}
/* ================================================================
HERO ANIMATION — cycles the five formulas on f(x) = sin(x)
================================================================ */
function initHero() {
const pal = NAW.graphPalette();
if (_heroTmr) { clearInterval(_heroTmr); _heroTmr = null; }
const hFn = x => Math.sin(x);
const hD1 = x => Math.cos(x);
const hx0 = 1.0, hh = 0.45;
const draw = idx => {
const F = FORMULAS[idx % FORMULAS.length];
D.heroLbl.textContent = `formula ${idx + 1}`;
const W = 520, H = 240;
const pL = 34, pR = 12, pT = 16, pB = 28;
const pW = W - pL - pR, pH = H - pT - pB;
const xMin = hx0 - 1.5, xMax = hx0 + 1.5;
const yLo = -1.6, yHi = 1.6;
const tx = x => pL + (x - xMin) / (xMax - xMin) * pW;
const ty = y => pT + (1 - (y - yLo) / (yHi - yLo)) * pH;
const clampY = y => Math.max(pT, Math.min(pT + pH, ty(y)));
let p = '', pen = false;
for (let i = 0; i <= 300; i++) {
const x = xMin + (xMax - xMin) * i / 300, y = hFn(x);
const py = clampY(ty(y)).toFixed(1);
p += pen ? ` L${tx(x).toFixed(1)} ${py}` : `M${tx(x).toFixed(1)} ${py}`;
pen = true;
}
let svg = `<svg viewBox="0 0 ${W} ${H}" xmlns="http://www.w3.org/2000/svg">`;
for (let i = 0; i <= 5; i++) {
svg += `<line x1="${(pL + i * pW / 5).toFixed(0)}" y1="${pT}" x2="${(pL + i * pW / 5).toFixed(0)}" y2="${pT + pH}" stroke="rgba(${pal.gridRGB},.2)" stroke-width="1"/>`;
svg += `<line x1="${pL}" y1="${(pT + i * pH / 5).toFixed(0)}" x2="${pL + pW}" y2="${(pT + i * pH / 5).toFixed(0)}" stroke="rgba(${pal.gridRGB},.2)" stroke-width="1"/>`;
}
const xAY = ty(0).toFixed(1);
svg += `<line x1="${pL}" y1="${xAY}" x2="${pL + pW}" y2="${xAY}" stroke="${pal.axis}" stroke-width="1.5"/>`;
/* true tangent */
const tm = hD1(hx0), tb = hFn(hx0) - tm * hx0;
svg += `<line x1="${tx(xMin).toFixed(1)}" y1="${clampY(ty(tm * xMin + tb)).toFixed(1)}" x2="${tx(xMax).toFixed(1)}" y2="${clampY(ty(tm * xMax + tb)).toFixed(1)}" stroke="${pal.curve}" stroke-width="1.2" opacity="0.55"/>`;
/* the formula's own line */
const P = F.pts(hx0, hh), fP = P.map(hFn);
if (F.deriv === 1) {
const m = (fP[1] - fP[0]) / (P[1] - P[0]), b0 = fP[0] - m * P[0];
svg += `<line x1="${tx(xMin).toFixed(1)}" y1="${clampY(ty(m * xMin + b0)).toFixed(1)}" x2="${tx(xMax).toFixed(1)}" y2="${clampY(ty(m * xMax + b0)).toFixed(1)}" stroke="${pal.c}" stroke-width="1.5" stroke-dasharray="5 3" opacity=".9"/>`;
} else {
const [xa, xb, xc] = P, [ya, yb, yc] = fP;
const q = t =>
ya * (t - xb) * (t - xc) / ((xa - xb) * (xa - xc)) +
yb * (t - xa) * (t - xc) / ((xb - xa) * (xb - xc)) +
yc * (t - xa) * (t - xb) / ((xc - xa) * (xc - xb));
let pp = '', pn = false;
for (let i = 0; i <= 60; i++) {
const t = xMin + (xMax - xMin) * i / 60;
const py = clampY(ty(q(t))).toFixed(1);
pp += pn ? ` L${tx(t).toFixed(1)} ${py}` : `M${tx(t).toFixed(1)} ${py}`;
pn = true;
}
svg += `<path d="${pp}" fill="none" stroke="${pal.c}" stroke-width="1.5" stroke-dasharray="5 3" opacity=".9"/>`;
}
svg += `<path d="${p}" fill="none" stroke="${pal.curve}" stroke-width="2"/>`;
const actSet = new Set(P.map(v => v.toFixed(12)));
[[hx0, 'x\u2080'], [hx0 + hh, '+h'], [hx0 - hh, '\u2212h'], [hx0 + 2 * hh, '+2h'], [hx0 - 2 * hh, '\u22122h']].forEach(([px0, lbl]) => {
const yv = hFn(px0);
const on = actSet.has(px0.toFixed(12));
const col = on ? pal.c : pal.curve;
svg += `<circle cx="${tx(px0).toFixed(1)}" cy="${ty(yv).toFixed(1)}" r="${on ? 5 : 3.5}" fill="${col}" stroke="${pal.bgDeep}" stroke-width="1.2" ${on ? '' : 'opacity="0.45"'}/>`;
if (on) svg += `<text x="${tx(px0).toFixed(1)}" y="${(ty(yv) - 10).toFixed(1)}" text-anchor="middle" font-size="10" fill="${col}" font-family="IBM Plex Mono,monospace">${lbl}</text>`;
});
svg += `<rect x="${pL + 6}" y="${pT + 6}" width="330" height="18" rx="2" fill="rgba(${pal.bgDeepRGB},.75)"/>`;
svg += `<text x="${pL + 13}" y="${pT + 19}" font-size="10" fill="${pal.axis}" font-family="IBM Plex Mono,monospace">${escHtml(F.short)} · ${escHtml(F.formula)}</text>`;
svg += '</svg>';
D.heroGr.innerHTML = svg;
};
draw(0);
let hi = 0;
_heroTmr = setInterval(() => { hi = (hi + 1) % FORMULAS.length; draw(hi); }, 1700);
}
/* ================================================================
EVENT LISTENERS (every shared button guarded by isActive())
================================================================ */
$('bisection-form').addEventListener('submit', solve);
$('reset-btn').addEventListener('click', reset);
D.prevBtn.addEventListener('click', () => goTo(_idx - 1));
D.nextBtn.addEventListener('click', () => goTo(_idx + 1));
D.playBtn.addEventListener('click', togglePlay);
D.speedSel.addEventListener('change', () => {
if (isActive() && _playTmr) { togglePlay(); togglePlay(); }
});
D.expImg.addEventListener('click', exportImage);
D.expPdf.addEventListener('click', exportPDF);
D.expGif.addEventListener('click', exportGIF);
D.precisionIn.addEventListener('input', () => {
if (isActive() && _res.length) {
renderSolBox(); renderTable(); renderGraph(_idx);
}
});
$('load-example').addEventListener('click', () => {
if (!isActive()) return;
const ex = EXAMPLES[_exIdx++ % EXAMPLES.length];
D.fxInput.value = ex.fx;
D.aInput.value = ex.x0;
const hi = $('h-input');
if (hi) hi.value = ex.h;
D.fxDot.className = 'validity-dot ok';
clearStatus();
showStatus(`Example loaded: ${ex.note}`, 'success');
});
/* ================================================================
METHOD-CHANGE HOOK
Enter: configure shared chrome for this sheet, start the hero.
Leave: restore every shared element, stop the hero, clear results.
================================================================ */
NAW.onMethodChange((newId, oldId) => {
if (newId in METHODS) {
applySheetChrome();
initHero();
} else if (oldId in METHODS) {
restoreChrome();
hideResults();
if (_heroTmr) { clearInterval(_heroTmr); _heroTmr = null; }
}
});
})();