Repository navigation
Expand file tree
/
Copy pathengine-open.js
More file actions
1028 lines (938 loc) · 46.7 KB
/
Copy pathengine-open.js
File metadata and controls
1028 lines (938 loc) · 46.7 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
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ====================================================================
ENGINE — Open methods (Newton-Raphson, Secant)
----------------------------------------------------------------------
Unlike engine-bracketing.js, these methods don't narrow a [a, b]
bracket that's guaranteed to contain the root — they walk forward
from one (Newton) or two (Secant) starting points, with no sign-
change requirement at all. Both share the same iteration shape:
reference point(s) → next approximation c → shift forward
so a single runOpenMethod() loop drives both; only the formula for
c and the shift rule differ (see method.kind below).
Requires core.js (shared plumbing + the method registry/switch UI)
to be loaded first, and reuses engine-bracketing.js's bracket
scanner (NAW.findBracketAutoWhole/Fine) to suggest starting guesses.
==================================================================== */
(function () {
'use strict';
const NAW = window.NAW;
const {
$, D, compileFn, parseVal, fmt, fmtE,
escHtml, showStatus, clearStatus,
dl, ts, canvasBlob, mkCaptureOverlay, waitFrames,
} = NAW;
/* ================================================================
STATE
================================================================ */
let _steps = [];
let _idx = 0;
let _playTmr = null;
let _heroTmr = null;
let _fn = null; // compiled f(x)
let _dfn = null; // compiled f'(x) — Newton only (symbolic via math.js)
let _dfnExpr = ''; // f'(x) as text, for display
let _xMin, _xMax; // plot range, computed from the whole run's history
let _trueRoot;
let _exIdx = 0;
const isActive = () => (NAW.getActiveMethod() in METHODS);
/* ================================================================
EXAMPLES
Newton needs one starting guess; Secant needs two.
================================================================ */
const NEWTON_EXAMPLES = [
{ fx: 'x^3 - x - 2', a: '1.5', note: 'Classic cubic — root ≈ 1.5214' },
{ fx: 'cos(x) - x', a: '0.8', note: 'Transcendental — root ≈ 0.7391' },
{ fx: 'x^2 - 2', a: '1.4', note: '√2 — root ≈ 1.4142' },
{ fx: 'exp(x) - 3*x', a: '0.5', note: 'Exponential — has two roots, guess steers which one' },
{ fx: 'x^3 - 4*x - 9', a: '2.5', note: 'Cubic — root ≈ 2.7065' },
];
const SECANT_EXAMPLES = [
{ fx: 'x^3 - x - 2', a: '1', b: '2', note: 'Classic cubic — root ≈ 1.5214' },
{ fx: 'cos(x) - x', a: '0', b: '1', note: 'Transcendental — root ≈ 0.7391' },
{ fx: 'x^2 - 2', a: '1', b: '2', note: '√2 — root ≈ 1.4142' },
{ fx: 'sin(x) - x/2', a: '1', b: '2', note: 'Trig — root ≈ 1.8955' },
{ fx: 'ln(x) - cos(x)', a: '1', b: '2', note: 'Natural log vs cosine — root ≈ 1.3029' },
];
/* ================================================================
METHODS
kind: 'newton' | 'secant' drives the loop formula, table shape,
and graph line (tangent vs secant line) below.
================================================================ */
const METHODS = {
newton: {
id: 'newton',
num: '03',
kind: 'newton',
docTitle: 'Newton-Raphson Method',
heroTitleHTML: 'Newton-Raphson,<br>chasing the <span class="accent">tangent line</span>.',
heroSub: 'Give it an equation and a starting guess. Each step draws the tangent line at the current point and jumps to where that line crosses zero — usually converging much faster than bracketing methods.',
metaMethod: 'Newton-Raphson (open method)',
metaOrder: 'Quadratic convergence (near the root)',
metaNeeds: 'a starting guess + f′(x) ≠ 0',
cLabel: 'c (next guess)',
cColHeader: 'c = a − f(a)/f\u2032(a)',
aeFallbackNote: '|c − a| (change between successive guesses — not a guaranteed bound)',
graphAria: 'Plot of f(x) with the Newton-Raphson tangent line at each step',
heroGraphAria: 'Animated demo of Newton-Raphson converging via tangent lines',
needsMsg: "Newton-Raphson needs f′(x) ≠ 0 at the starting guess.",
hideB: true,
shapeCopy: {
'bracket-legend': 'Starting guess',
'a-input-label': 'a (initial guess)',
'bracket-auto-label': 'Suggest a starting guess automatically',
'bracket-auto-hint': 'scans for a sign change, then starts from whichever end is closer to f(x) = 0',
'bracket-manual-label': "I'll set the initial guess myself",
'bracket-manual-hint': 'type your own starting value below — as given by your instructor, if any',
'read-a-label': 'a', 'read-b-label': "f\u2032(a)", 'read-fc-label': 'f(c)',
},
},
secant: {
id: 'secant',
num: '04',
kind: 'secant',
docTitle: 'Secant Method',
heroTitleHTML: 'Secant method,<br>no derivative <span class="accent">required</span>.',
heroSub: 'Give it an equation and two starting points. Each step draws the line through the last two points and jumps to where it crosses zero — like false position, but both points always slide forward, with no sign-change requirement.',
metaMethod: 'Secant (open method)',
metaOrder: 'Superlinear convergence (≈1.618 order)',
metaNeeds: 'two starting guesses, x₀ ≠ x₁',
cLabel: 'x₂ (next guess)',
cColHeader: 'x\u2082 = (x\u2080\u00b7f(x\u2081) \u2212 x\u2081\u00b7f(x\u2080)) / (f(x\u2081) \u2212 f(x\u2080))',
aeFallbackNote: '|x\u2082 \u2212 x\u2081| (change between successive guesses — not a guaranteed bound)',
graphAria: 'Plot of f(x) with the secant line at each step',
heroGraphAria: 'Animated demo of the secant method sliding two points forward',
needsMsg: 'Secant needs two distinct starting points with f(x\u2080) \u2260 f(x\u2081).',
hideB: false,
shapeCopy: {
'bracket-legend': 'Starting points',
'a-input-label': 'x\u2080 (first guess)',
'b-input-label': 'x\u2081 (second guess)',
'bracket-auto-label': 'Suggest two starting points automatically',
'bracket-auto-hint': 'scans f(x) for a sign change and uses both endpoints — no sign change is actually required',
'bracket-manual-label': "I'll set x\u2080 and x\u2081 myself",
'bracket-manual-hint': 'type your own starting points below — they do not need opposite signs',
'read-a-label': 'x\u2080', 'read-b-label': 'x\u2081', 'read-fc-label': 'f(x\u2082)',
},
},
};
Object.assign(NAW.METHODS, METHODS);
/* ================================================================
DERIVATIVE (Newton only) — symbolic, via math.js
================================================================ */
function compileDerivative(expr) {
try {
const processed = NAW.remapLogNotation(NAW.preprocessExpr(expr.trim()));
const node = math.parse(processed);
const dnode = math.derivative(node, 'x');
const scope = {};
const fn = x => {
scope.x = x;
const r = dnode.evaluate(scope);
return typeof r === 'number' ? r : NaN;
};
fn.text = dnode.toString({ implicit: 'hide' });
return fn;
} catch { return null; }
}
/* ================================================================
OPEN-METHOD ALGORITHM (shared engine for both Newton & Secant)
p, q are the current reference point(s); c is the next
approximation. See the header comment for the shift rule.
stopMode values match the bracketing engine: 'c-repeat' (default),
'auto' (legacy — here read as |c - prev| below machine epsilon),
'iterations', 'tolerance'.
================================================================ */
function runOpenMethod(fn, dfn, p0, q0, mode, param, trueRoot, kind) {
const out = [];
let p = p0, q = q0;
let prevC = NaN;
const maxN = (mode === 'iterations') ? Math.min(param, 200) : 100;
const tol = (mode === 'tolerance') ? param : 0;
for (let n = 1; n <= maxN; n++) {
const fp = fn(p);
const fq = (kind === 'secant') ? fn(q) : undefined;
let c, step;
if (kind === 'newton') {
const fpp = dfn(p);
if (!isFinite(fpp) || Math.abs(fpp) < 1e-14) {
step = { n, a: p, fa: fp, fpa: fpp, c: NaN, fc: NaN, ae: NaN, re: NaN,
converged: true, reason: "f′(x) ≈ 0 — tangent is flat, Newton-Raphson cannot continue" };
out.push(step);
break;
}
c = p - fp / fpp;
const fc = fn(c);
step = { n, a: p, fa: fp, fpa: fpp, c, fc, converged: false, reason: '' };
} else {
if (Math.abs(fq - fp) < 1e-300) {
step = { n, x0: p, x1: q, fx0: fp, fx1: fq, x2: NaN, fx2: NaN, ae: NaN, re: NaN,
converged: true, reason: "f(x\u2080) = f(x\u2081) — the secant line is horizontal, cannot continue" };
out.push(step);
break;
}
c = (p * fq - q * fp) / (fq - fp);
const fc = fn(c);
step = { n, x0: p, x1: q, fx0: fp, fx1: fq, x2: c, fx2: fc, converged: false, reason: '' };
}
/* AE / RE */
const cVal = (kind === 'newton') ? step.c : step.x2;
const fcVal = (kind === 'newton') ? step.fc : step.fx2;
let ae, re;
if (trueRoot != null && isFinite(trueRoot)) {
ae = Math.abs(cVal - trueRoot);
re = Math.abs(trueRoot) > 1e-14 ? ae / Math.abs(trueRoot) : NaN;
} else {
ae = Math.abs(cVal - (kind === 'newton' ? p : q));
re = Math.abs(cVal) > 1e-14 ? ae / Math.abs(cVal) : NaN;
}
step.ae = ae; step.re = re;
out.push(step);
if (Math.abs(fcVal) === 0) { step.converged = true; step.reason = 'f(c) = 0 exactly'; break; }
if (mode === 'c-repeat' && n > 1 && fmt(cVal) === fmt(prevC)) {
step.converged = true; step.reason = 'c repeated — root resolved to displayed precision'; break;
}
if (mode === 'auto' && n > 1 && Math.abs(cVal - prevC) < 4 * Number.EPSILON * Math.max(1, Math.abs(cVal))) {
step.converged = true; step.reason = 'machine precision reached'; break;
}
if (mode === 'tolerance' && tol > 0 && ae <= tol) {
step.converged = true; step.reason = `AE ≤ ${tol}`; break;
}
if (!isFinite(cVal)) { step.converged = true; step.reason = 'diverged — no finite next value'; break; }
prevC = cVal;
if (kind === 'newton') { p = cVal; }
else { p = q; q = cVal; }
}
if (out.length && !out[out.length - 1].converged) {
out[out.length - 1].converged = true;
out[out.length - 1].reason = (mode === 'iterations')
? `${out.length} iterations reached` : 'max iterations reached';
}
return out;
}
/* ================================================================
MINI NUMBER LINE — same idea as the bracketing engine's, but the
range comes from the whole run's history (there's no fixed
[_initA,_initB] bracket to draw against here).
================================================================ */
function miniLine(pos, cur) {
const pal = NAW.graphPalette();
const W = 148, H = 26, pad = 11;
const rng = (_xMax - _xMin) || 1;
const tx = v => pad + ((v - _xMin) / rng) * (W - 2 * pad);
const px = tx(pos), cx = tx(cur), mid = H / 2;
return [
`<svg viewBox="0 0 ${W} ${H}" width="${W}" height="${H}" xmlns="http://www.w3.org/2000/svg">`,
`<line x1="${pad}" y1="${mid}" x2="${W - pad}" y2="${mid}" stroke="${pal.miniTrack}" stroke-width="2"/>`,
`<line x1="${pad}" y1="${mid-4}" x2="${pad}" y2="${mid+4}" stroke="${pal.tickLine}" stroke-width="1.5"/>`,
`<line x1="${W - pad}" y1="${mid-4}" x2="${W - pad}" y2="${mid+4}" stroke="${pal.tickLine}" stroke-width="1.5"/>`,
`<line x1="${px}" y1="${mid-7}" x2="${px}" y2="${mid+7}" stroke="${pal.curve}" stroke-width="2" stroke-linecap="round"/>`,
`<circle cx="${cx}" cy="${mid}" r="4" fill="${pal.c}" stroke="${pal.bgDeep}" stroke-width="1.2"/>`,
`</svg>`
].join('');
}
/* ================================================================
RENDER: SOLUTION BOX
================================================================ */
function renderSolBox() {
const kind = NAW.METHODS[NAW.getActiveMethod()].kind;
const last = _steps[_steps.length - 1];
const hasTrue = (_trueRoot != null && isFinite(_trueRoot));
const cVal = kind === 'newton' ? last.c : last.x2;
let startBlock;
if (kind === 'newton') {
startBlock = `
<div class="sol-group">
<div class="sol-lbl">Starting guess</div>
<div class="bracket-box">
<div class="bc-row"><code>a\u2080 = ${fmt(_steps[0].a)}</code></div>
<div class="bc-row"><code>f(a\u2080) = ${fmt(_steps[0].fa)}</code></div>
<div class="bc-row"><code>f\u2032(x) = ${escHtml(_dfnExpr)}</code>
<span class="ivt-note">\u2192 computed symbolically — no manual differentiation needed</span></div>
</div>
</div>`;
} else {
startBlock = `
<div class="sol-group">
<div class="sol-lbl">Starting points — no sign change required</div>
<div class="bracket-box">
<div class="bc-row"><code>x\u2080 = ${fmt(_steps[0].x0)}, f(x\u2080) = ${fmt(_steps[0].fx0)}</code></div>
<div class="bc-row"><code>x\u2081 = ${fmt(_steps[0].x1)}, f(x\u2081) = ${fmt(_steps[0].fx1)}</code></div>
</div>
</div>`;
}
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>
${startBlock}
<div class="sol-group">
<div class="sol-lbl">Result — after ${_steps.length} iteration${_steps.length !== 1 ? 's' : ''}</div>
<div class="result-row">
<span class="root-chip">Root \u2248 ${fmt(cVal)}</span>
${last.converged ? `<span class="conv-chip">\u2713 ${escHtml(last.reason)}</span>` : ''}
${hasTrue ? `<span class="ae-note">true absolute error: ${fmtE(Math.abs(cVal - _trueRoot))}</span>` : ''}
</div>
</div>
`;
}
/* ================================================================
RENDER: ITERATION TABLE
================================================================ */
function renderTable() {
const m = NAW.METHODS[NAW.getActiveMethod()];
const kind = m.kind;
const hasTrue = (_trueRoot != null && isFinite(_trueRoot));
const last = _steps[_steps.length - 1];
const sc = v => (v == null || isNaN(v)) ? '' : (v < 0 ? 'neg-val' : (v > 0 ? 'pos-val' : ''));
if (kind === 'newton') {
D.tHead.innerHTML = ['Step','a','f(a)','f\u2032(a)', m.cColHeader, 'f(c)','AE','RE','Position']
.map(h => `<th>${h}</th>`).join('');
D.tBody.innerHTML = '';
for (const s of _steps) {
const tr = document.createElement('tr');
if (s.n === _idx + 1) tr.classList.add('active-row');
if (s.converged) tr.classList.add('converged-row');
tr.innerHTML = [
`<td>${s.n}</td>`,
`<td>${fmt(s.a)}</td>`,
`<td class="${sc(s.fa)}">${fmt(s.fa)}</td>`,
`<td>${fmt(s.fpa)}</td>`,
`<td class="c-val">${fmt(s.c)}</td>`,
`<td class="${sc(s.fc)}">${fmt(s.fc)}</td>`,
`<td>${fmtE(s.ae)}</td>`,
`<td>${(s.re != null && !isNaN(s.re)) ? fmtE(s.re) : '\u2014'}</td>`,
`<td class="mini-cell">${isFinite(s.c) ? miniLine(s.a, s.c) : '\u2014'}</td>`,
].join('');
D.tBody.appendChild(tr);
}
} else {
D.tHead.innerHTML = ['Step','x\u2080','x\u2081','f(x\u2080)','f(x\u2081)', m.cColHeader.split(' = ')[0], 'f(x\u2082)','AE','RE','Position']
.map(h => `<th>${h}</th>`).join('');
D.tBody.innerHTML = '';
for (const s of _steps) {
const tr = document.createElement('tr');
if (s.n === _idx + 1) tr.classList.add('active-row');
if (s.converged) tr.classList.add('converged-row');
tr.innerHTML = [
`<td>${s.n}</td>`,
`<td>${fmt(s.x0)}</td>`,
`<td>${fmt(s.x1)}</td>`,
`<td class="${sc(s.fx0)}">${fmt(s.fx0)}</td>`,
`<td class="${sc(s.fx1)}">${fmt(s.fx1)}</td>`,
`<td class="c-val">${fmt(s.x2)}</td>`,
`<td class="${sc(s.fx2)}">${fmt(s.fx2)}</td>`,
`<td>${fmtE(s.ae)}</td>`,
`<td>${(s.re != null && !isNaN(s.re)) ? fmtE(s.re) : '\u2014'}</td>`,
`<td class="mini-cell">${isFinite(s.x2) ? miniLine(s.x1, s.x2) : '\u2014'}</td>`,
].join('');
D.tBody.appendChild(tr);
}
}
const cVal = kind === 'newton' ? last.c : last.x2;
D.capSum.textContent =
`f(x) = ${D.fxInput.value.trim()}` +
` \u00b7 ${_steps.length} iteration${_steps.length !== 1 ? 's' : ''}` +
` \u00b7 root \u2248 ${fmt(cVal)}${last.converged ? ' \u2713' : ''}`;
D.tblNote.textContent = hasTrue
? `AE = |c \u2212 ${fmt(_trueRoot)}| (true root), RE = AE / |true root|`
: `AE = ${m.aeFallbackNote}, RE = AE / |c|`;
}
/* ================================================================
RENDER: MAIN GRAPH
Draws the tangent line (Newton) or secant line (Secant) for the
current step, extended across the plot and marked where it
crosses zero at c — same visual language as the bracketing graph.
================================================================ */
function renderGraph(idx) {
const pal = NAW.graphPalette();
if (!_steps.length || !_fn) return;
const kind = NAW.METHODS[NAW.getActiveMethod()].kind;
const s = _steps[idx];
const W = 800, H = 456;
const pL = 72, pR = 24, pT = 30, pB = 82;
const pW = W - pL - pR, pH = H - pT - pB;
const rng = (_xMax - _xMin) || 2;
const xMin = _xMin - rng * 0.15;
const xMax = _xMax + rng * 0.15;
const N = 500;
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 - 4}" 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>`;
/* Historical c dots along the axis */
if (idx > 0) {
const span = Math.max(idx - 1, 1);
for (let i = 0; i < idx; i++) {
const pc = kind === 'newton' ? _steps[i].c : _steps[i].x2;
if (!isFinite(pc)) continue;
const pcX = tx(pc).toFixed(1);
const age = idx - 1 - i;
const op = (0.70 - 0.52 * age / span).toFixed(2);
svg += `<line x1="${pcX}" y1="${pT}" x2="${pcX}" y2="${pT + pH}" stroke="${pal.c}" stroke-width="1.3" stroke-dasharray="3 5" opacity="${op}"/>`;
svg += `<circle cx="${pcX}" cy="${(pT + pH).toFixed(1)}" r="2.8" fill="${pal.c}" opacity="${op}"/>`;
}
}
/* Function curve */
svg += `<path d="${path}" fill="none" stroke="${pal.curve}" stroke-width="2.5" stroke-linejoin="round" stroke-linecap="round"/>`;
/* The tangent (Newton) or secant (Secant) line for this step */
let m, b, p1x, p2x;
if (kind === 'newton') {
m = s.fpa; b = s.fa - s.fpa * s.a;
p1x = s.a; p2x = s.a;
} else {
m = (s.fx1 - s.fx0) / (s.x1 - s.x0); b = s.fx0 - m * s.x0;
p1x = s.x0; p2x = s.x1;
}
if (isFinite(m)) {
const y1 = clampY(ty(m * xMin + b)), y2 = clampY(ty(m * xMax + b));
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="5 3" opacity="0.85"/>`;
}
/* Points on curve + drop lines */
const plotPt = (xv, lbl, col, r) => {
const yv = _fn(xv);
if (!isFinite(yv)) return '';
const px = tx(xv).toFixed(1), py = ty(yv).toFixed(1);
const axY = isFinite(ty(0)) ? clampY(ty(0)).toFixed(1) : (pT + pH);
return [
`<line x1="${px}" y1="${py}" x2="${px}" y2="${axY}" stroke="${col}" stroke-width="1" stroke-dasharray="3 3" opacity="0.45"/>`,
`<circle cx="${px}" cy="${py}" r="${r}" fill="${col}" stroke="${pal.bgDeep}" stroke-width="1.5"/>`,
`<text x="${px}" y="${+py - r - 4}" text-anchor="middle" font-size="11" fill="${col}" font-family="IBM Plex Mono,monospace" font-weight="500">${lbl}</text>`,
].join('');
};
if (kind === 'newton') {
svg += plotPt(s.a, 'a', pal.curve, 5);
if (isFinite(s.c)) svg += plotPt(s.c, 'c', pal.c, 6.5);
} else {
svg += plotPt(s.x0, 'x\u2080', pal.curve, 5);
svg += plotPt(s.x1, 'x\u2081', pal.curve, 5);
if (isFinite(s.x2)) svg += plotPt(s.x2, 'x\u2082', pal.c, 6.5);
}
const cValLbl = kind === 'newton' ? fmt(s.c) : fmt(s.x2);
svg += `<rect x="${pL + 6}" y="${pT + 6}" width="320" 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">` +
`Step ${s.n}${s.converged ? ' \u00b7 ' + escHtml(s.reason) : ` \u00b7 next = ${cValLbl}`}</text>`;
svg += '</svg>';
D.bisGr.innerHTML = svg;
/* Readings — reuse the shared a/b/c/f(c) readouts */
if (kind === 'newton') {
D.readA.textContent = fmt(s.a);
D.readB.textContent = fmt(s.fpa);
D.readC.textContent = isFinite(s.c) ? fmt(s.c) : '\u2014';
D.readFc.textContent = isFinite(s.fc) ? fmt(s.fc) : '\u2014';
} else {
D.readA.textContent = fmt(s.x0);
D.readB.textContent = fmt(s.x1);
D.readC.textContent = isFinite(s.x2) ? fmt(s.x2) : '\u2014';
D.readFc.textContent = isFinite(s.fx2) ? fmt(s.fx2) : '\u2014';
}
if (s.converged) {
D.readConvW.hidden = false;
D.readConv.textContent = s.reason;
} else {
D.readConvW.hidden = true;
}
D.stepInd.textContent = `Step ${s.n} of ${_steps.length}`;
D.prevBtn.disabled = (idx === 0);
D.nextBtn.disabled = (idx >= _steps.length - 1);
Array.from(D.tBody.querySelectorAll('tr')).forEach((r, i) => {
r.classList.toggle('active-row', i === idx);
});
}
/* ================================================================
HERO ANIMATION — small always-running demo in the page header
================================================================ */
function initHero(kind) {
const pal = NAW.graphPalette();
if (_heroTmr) { clearInterval(_heroTmr); _heroTmr = null; }
const hFn = x => x * x * x - x - 2;
const hDfn = x => 3 * x * x - 1;
const hSteps = [];
if (kind === 'newton') {
let a = 1.9;
for (let i = 0; i < 7; i++) {
const fa = hFn(a), fpa = hDfn(a);
if (Math.abs(fpa) < 1e-8) break;
const c = a - fa / fpa;
hSteps.push({ p1: a, p2: a, c });
a = c;
}
} else {
let x0 = 1, x1 = 2;
for (let i = 0; i < 7; i++) {
const f0 = hFn(x0), f1 = hFn(x1);
if (Math.abs(f1 - f0) < 1e-12) break;
const c = (x0 * f1 - x1 * f0) / (f1 - f0);
hSteps.push({ p1: x0, p2: x1, c });
x0 = x1; x1 = c;
}
}
if (!hSteps.length) hSteps.push({ p1: 1, p2: 2, c: 1.5 });
const draw = idx => {
const s = hSteps[idx];
D.heroLbl.textContent = `step ${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 yLo = -6, yHi = 6;
const tx = x => pL + (x - 0.6) / 1.8 * pW;
const ty = y => pT + (1 - (y - yLo) / (yHi - yLo)) * pH;
const clampY = y => Math.max(pT, Math.min(pT + pH, y));
let p = '', pen = false;
for (let i = 0; i <= 300; i++) {
const x = 0.6 + 1.8 * i / 300, y = hFn(x);
if (!isFinite(y) || y < yLo - 1 || y > yHi + 1) { pen = false; continue; }
const py = clampY(ty(y)).toFixed(1);
p += pen ? ` L${tx(x).toFixed(1)} ${py}` : `M${tx(x).toFixed(1)} ${py}`;
pen = true;
}
const xAY = ty(0).toFixed(1);
const cX = tx(s.c).toFixed(1);
let m, b;
if (kind === 'newton') { m = hDfn(s.p1); b = hFn(s.p1) - m * s.p1; }
else { m = (hFn(s.p2) - hFn(s.p1)) / (s.p2 - s.p1); b = hFn(s.p1) - m * s.p1; }
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"/>`;
}
svg += `<line x1="${pL}" y1="${xAY}" x2="${pL + pW}" y2="${xAY}" stroke="${pal.axis}" stroke-width="1.5"/>`;
if (isFinite(m)) {
const y1 = clampY(ty(m * 0.6 + b)).toFixed(1), y2 = clampY(ty(m * 2.4 + b)).toFixed(1);
svg += `<line x1="${tx(0.6).toFixed(1)}" y1="${y1}" x2="${tx(2.4).toFixed(1)}" y2="${y2}" stroke="${pal.c}" stroke-width="1.5" stroke-dasharray="4 3" opacity=".85"/>`;
}
svg += `<path d="${p}" fill="none" stroke="${pal.curve}" stroke-width="2"/>`;
const cY = hFn(s.c);
if (isFinite(cY)) svg += `<circle cx="${cX}" cy="${clampY(ty(cY)).toFixed(1)}" r="5" fill="${pal.c}" stroke="${pal.bgDeep}" stroke-width="1.5"/>`;
svg += `<text x="${cX}" y="${H - 5}" text-anchor="middle" font-size="11" fill="${pal.c}" font-family="IBM Plex Mono,monospace">c</text>`;
svg += '</svg>';
D.heroGr.innerHTML = svg;
};
draw(0);
let hi = 0;
_heroTmr = setInterval(() => { hi = (hi + 1) % hSteps.length; draw(hi); }, 1650);
}
/* ================================================================
SOLVE
================================================================ */
function solve(e) {
if (!isActive()) return;
e?.preventDefault();
clearStatus();
if (_playTmr) { clearInterval(_playTmr); _playTmr = null; D.playBtn.textContent = '\u25b6'; }
const kind = NAW.METHODS[NAW.getActiveMethod()].kind;
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.`);
let dfn = null;
if (kind === 'newton') {
dfn = compileDerivative(fxRaw);
if (!dfn) return showStatus(`Could not compute f′(x) for "${escHtml(fxRaw)}" symbolically. Try simplifying the expression.`);
}
/* --- starting point(s): auto-suggested, or typed manually --- */
const _bm = document.querySelector('[name="bracketMode"]:checked')?.value ?? '';
const guessMode = (_bm === 'auto' || _bm === 'manual') ? _bm : 'auto';
let p0, q0;
if (guessMode === 'manual') {
const aRaw = D.aInput.value.trim();
if (!aRaw) return showStatus(kind === 'newton' ? 'Enter a starting guess a.' : 'Enter both starting points x\u2080 and x\u2081.');
if (aRaw.length > 200) return showStatus('Value expression is too long (max 200 characters).');
p0 = parseVal(aRaw);
if (isNaN(p0)) return showStatus(`Cannot evaluate "${aRaw}". Use a number or an expression like e, pi, 2*pi.`);
if (kind === 'secant') {
const bRaw = D.bInput.value.trim();
if (!bRaw) return showStatus('Enter both starting points x\u2080 and x\u2081.');
q0 = parseVal(bRaw);
if (isNaN(q0)) return showStatus(`Cannot evaluate "${bRaw}". Use a number or an expression like e, pi, 2*pi.`);
if (p0 === q0) return showStatus('x\u2080 and x\u2081 must be different values.');
}
D.bracketHint.hidden = true;
} else {
const wantFine = D.fineToggle.checked;
const wantNegPref = $('bracket-neg-toggle').checked;
let found = wantFine
? NAW.findBracketAutoFine(fn, wantNegPref)
: NAW.findBracketAutoWhole(fn, wantNegPref);
let usedFine = wantFine;
if (!found && !wantFine) { found = NAW.findBracketAutoFine(fn, wantNegPref); usedFine = true; }
if (!found) return showStatus('Could not automatically find a useful starting point for this function within \u00b11000. Switch to manual entry and set a starting value directly.');
const [lo, hi] = found;
if (kind === 'newton') {
/* Pick whichever endpoint's f-value is closer to zero as the seed. */
const flo = fn(lo), fhi = fn(hi);
p0 = Math.abs(flo) <= Math.abs(fhi) ? lo : hi;
D.aInput.value = fmt(p0);
D.bracketHint.hidden = false;
D.bracketHint.textContent =
(usedFine ? 'Auto-suggested from a scanned sign change (tighter decimal scan)' : 'Auto-suggested from a scanned sign change') +
`: a = ${fmt(p0)} (closer to f(x) = 0 of the two endpoints found)`;
} else {
p0 = lo; q0 = hi;
D.aInput.value = fmt(p0);
D.bInput.value = fmt(q0);
D.bracketHint.hidden = false;
D.bracketHint.textContent =
(usedFine ? 'Auto-suggested tighter decimal points' : 'Auto-suggested whole-number points') +
`: x\u2080 = ${fmt(p0)}, x\u2081 = ${fmt(q0)}`;
}
}
if (kind === 'newton') {
const fp0 = fn(p0);
if (!isFinite(fp0)) return showStatus(`f(a) = f(${fmt(p0)}) is not finite. Check your function and starting guess.`);
if (fp0 === 0) return showStatus(`a = ${fmt(p0)} is already a root — f(a) = 0!`, 'success');
const dp0 = dfn(p0);
if (!isFinite(dp0) || Math.abs(dp0) < 1e-14) return showStatus(`f′(${fmt(p0)}) \u2248 0 — the tangent line is flat here. Try a different starting guess.`);
} else {
const fp0 = fn(p0), fq0 = fn(q0);
if (!isFinite(fp0)) return showStatus(`f(x\u2080) = f(${fmt(p0)}) is not finite. Check your function and starting points.`);
if (!isFinite(fq0)) return showStatus(`f(x\u2081) = f(${fmt(q0)}) is not finite. Check your function and starting points.`);
if (fp0 === 0) return showStatus(`x\u2080 = ${fmt(p0)} is already a root — f(x\u2080) = 0!`, 'success');
if (fq0 === 0) return showStatus(`x\u2081 = ${fmt(q0)} is already a root — f(x\u2081) = 0!`, 'success');
if (fp0 === fq0) return showStatus(`f(x\u2080) = f(x\u2081) = ${fmt(fp0)} — the secant line would be horizontal. Choose different starting points.`);
}
const trRaw = D.trueIn.value.trim();
_trueRoot = trRaw ? parseVal(trRaw) : null;
const _sm = document.querySelector('[name="stopMode"]:checked')?.value ?? '';
const mode = (['c-repeat','auto','iterations','tolerance'].includes(_sm)) ? _sm : 'c-repeat';
let param = null;
if (mode === 'iterations') {
param = parseInt($('iter-count').value);
if (isNaN(param) || param < 1) return showStatus('Enter a valid iteration count (\u2265 1).');
} else if (mode === 'tolerance') {
param = parseFloat($('tol-value').value);
if (isNaN(param) || param <= 0) return showStatus('Enter a valid positive tolerance.');
}
_fn = fn; _dfn = dfn; _dfnExpr = dfn ? dfn.text : '';
_steps = runOpenMethod(fn, dfn, p0, q0, mode, param, _trueRoot, kind);
if (!_steps.length) return showStatus('No steps produced — check your inputs.');
/* Plot range from every point visited across the whole run */
const allX = [];
for (const s of _steps) {
if (kind === 'newton') { allX.push(s.a); if (isFinite(s.c)) allX.push(s.c); }
else { allX.push(s.x0, s.x1); if (isFinite(s.x2)) allX.push(s.x2); }
}
_xMin = Math.min(...allX); _xMax = Math.max(...allX);
if (_xMax - _xMin < 1e-6) { _xMin -= 1; _xMax += 1; }
_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' });
}
/* ================================================================
PLAYBACK
================================================================ */
function goTo(idx) {
if (!isActive() || !_steps.length) return;
_idx = Math.max(0, Math.min(idx, _steps.length - 1));
renderGraph(_idx);
}
function togglePlay() {
if (!isActive() || !_steps.length) return;
if (_playTmr) {
clearInterval(_playTmr); _playTmr = null;
D.playBtn.textContent = '\u25b6';
D.playBtn.setAttribute('aria-label', 'Play');
} else {
if (_idx >= _steps.length - 1) _idx = -1;
D.playBtn.textContent = '\u23f8';
D.playBtn.setAttribute('aria-label', 'Pause');
_playTmr = setInterval(() => {
_idx++;
if (_idx >= _steps.length) {
clearInterval(_playTmr); _playTmr = null;
D.playBtn.textContent = '\u25b6';
D.playBtn.setAttribute('aria-label', 'Play');
return;
}
renderGraph(_idx);
}, +D.speedSel.value);
}
}
/* ================================================================
RESET
================================================================ */
function hideResults() {
if (_playTmr) { clearInterval(_playTmr); _playTmr = null; D.playBtn.textContent = '\u25b6'; }
clearStatus();
D.solSec.hidden = true;
D.vizSec.hidden = true;
D.tblSec.hidden = true;
_steps = []; _idx = 0; _fn = null; _dfn = null;
D.prevBtn.disabled = true;
D.nextBtn.disabled = true;
}
function reset() {
if (!isActive()) return;
hideResults();
D.fxInput.value = '';
D.aInput.value = '';
D.bInput.value = '';
D.trueIn.value = '';
D.fxDot.className = 'validity-dot';
$('bracket-mode-auto').checked = true;
D.aInput.disabled = true;
D.bInput.disabled = true;
document.querySelectorAll('#bracket-mode-options .stop-option').forEach(opt => opt.classList.remove('active-mode'));
$('bracket-mode-auto').closest('.stop-option').classList.add('active-mode');
D.fineToggle.checked = false;
$('bracket-neg-toggle').checked = false;
D.bracketHint.hidden = true;
}
/* ================================================================
EXPORTS
================================================================ */
function buildExportEl() {
const m = NAW.METHODS[NAW.getActiveMethod()];
const kind = m.kind;
const fx = escHtml(D.fxInput.value.trim());
const last = _steps[_steps.length - 1];
const cVal = kind === 'newton' ? last.c : last.x2;
const hasTrue = (_trueRoot != null && isFinite(_trueRoot));
const date = new Date().toLocaleDateString(undefined, { year:'numeric', month:'short', day:'numeric' });
const thS = 'padding:6px 9px;text-align:right;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 th1S = thS + ';text-align:left';
const cols = kind === 'newton'
? ['Step','a','f(a)','f\u2032(a)', m.cColHeader, 'f(c)','AE','RE']
: ['Step','x\u2080','x\u2081','f(x\u2080)','f(x\u2081)','x\u2082','f(x\u2082)','AE','RE'];
const thead = `<thead><tr>${cols.map((h,i)=>`<th style="${i===0?th1S:thS}">${h}</th>`).join('')}</tr></thead>`;
const tdB = 'padding:5px 9px;border-bottom:1px solid rgba(61,102,148,.2);text-align:right;white-space:nowrap';
const td1B = tdB + ';text-align:left';
const colr = v => (v < 0 ? '#D9776B' : '#7FA68C');
let rows = '';
for (const s of _steps) {
const rowBg = s.converged ? 'background:rgba(127,166,140,.1)' : '';
const reStr = (s.re != null && !isNaN(s.re)) ? fmtE(s.re) : '\u2014';
if (kind === 'newton') {
rows += `<tr style="${rowBg}">
<td style="${td1B}">${s.n}</td>
<td style="${tdB}">${fmt(s.a)}</td>
<td style="${tdB};color:${colr(s.fa)}">${fmt(s.fa)}</td>
<td style="${tdB}">${fmt(s.fpa)}</td>
<td style="${tdB};color:#E2945F;font-weight:600">${fmt(s.c)}</td>
<td style="${tdB};color:${isFinite(s.fc)?colr(s.fc):'#7B93B0'}">${fmt(s.fc)}</td>
<td style="${tdB}">${fmtE(s.ae)}</td>
<td style="${tdB}">${reStr}</td>
</tr>`;
} else {
rows += `<tr style="${rowBg}">
<td style="${td1B}">${s.n}</td>
<td style="${tdB}">${fmt(s.x0)}</td>
<td style="${tdB}">${fmt(s.x1)}</td>
<td style="${tdB};color:${colr(s.fx0)}">${fmt(s.fx0)}</td>
<td style="${tdB};color:${colr(s.fx1)}">${fmt(s.fx1)}</td>
<td style="${tdB};color:#E2945F;font-weight:600">${fmt(s.x2)}</td>
<td style="${tdB};color:${isFinite(s.fx2)?colr(s.fx2):'#7B93B0'}">${fmt(s.fx2)}</td>
<td style="${tdB}">${fmtE(s.ae)}</td>
<td style="${tdB}">${reStr}</td>
</tr>`;
}
}
const tblNote = hasTrue
? `AE = |c \u2212 ${fmt(_trueRoot)}| (true root), RE = AE / |true root|`
: `AE = ${m.aeFallbackNote}, RE = AE / |c|`;
const convNote = last.converged ? ` \u00b7 <span style="color:#7FA68C">\u2713 ${escHtml(last.reason)}</span>` : '';
const startNote = kind === 'newton'
? `<span>Starting guess a = ${fmt(_steps[0].a)}</span><span>f\u2032(x) = ${escHtml(_dfnExpr)}</span>`
: `<span>x\u2080 = ${fmt(_steps[0].x0)}</span><span>x\u2081 = ${fmt(_steps[0].x1)}</span>`;
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 \u00b7 ${m.docTitle}</div>
<div style="font-size:20px;font-weight:700;color:#EDEAE0;font-family:monospace">f(x) = ${fx}</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:17px;font-weight:700">Root \u2248 ${fmt(cVal)}</span><br>
${_steps.length} iteration${_steps.length!==1?'s':''}${convNote}
</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">Starting point${kind==='secant'?'s':''}</span>
${startNote}
</div>
<table style="width:100%;border-collapse:collapse;font-family:monospace;font-size:12px">
${thead}<tbody>${rows}</tbody>
</table>
<div style="font-size:10px;color:#7B93B0;margin-top:7px;font-family:monospace">${escHtml(tblNote)}</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 \u00b7 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() || !_steps.length) return;
const btn = D.expImg;
btn.textContent = 'Capturing\u2026'; btn.disabled = true;
const overlay = mkCaptureOverlay('Preparing Image\u2026');
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() || !_steps.length) return;
const btn = D.expPdf;
btn.textContent = 'Generating\u2026'; btn.disabled = true;
const overlay = mkCaptureOverlay('Preparing PDF\u2026');
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() || !_steps.length) return;
NAW.exportGraphGIF({
svgEl: D.bisGr,
totalSteps: _steps.length,
gotoStep: goTo,
currentIdx: _idx,
filename: `${NAW.getActiveMethod()}_${ts()}.gif`,
button: D.expGif,
});
}
/* ================================================================
EVENT LISTENERS
(bracketMode radio, precision input, and the sheet-item clicks
are already wired generically in engine-bracketing.js / core.js —
this engine only needs its own solve/reset/playback/export hooks,
since every button is guarded by isActive() above.)
================================================================ */
$('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() && _steps.length) {
renderSolBox(); renderTable(); renderGraph(_idx);
}
});
$('load-example').addEventListener('click', () => {
if (!isActive()) return;
const kind = NAW.METHODS[NAW.getActiveMethod()].kind;
if (kind === 'newton') {
const ex = NEWTON_EXAMPLES[_exIdx++ % NEWTON_EXAMPLES.length];
D.fxInput.value = ex.fx;
$('bracket-mode-manual').checked = true;
$('bracket-mode-manual').dispatchEvent(new Event('change'));
D.aInput.value = ex.a;
D.fxDot.className = 'validity-dot ok';