-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintro.html
More file actions
662 lines (552 loc) · 31.4 KB
/
intro.html
File metadata and controls
662 lines (552 loc) · 31.4 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
<!DOCTYPE html>
<html lang="uk">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NumMeth Lab</title>
<script src="https://cdn.plot.ly/plotly-2.24.1.min.js"></script>
<script>
window.MathJax = {
tex: {
inlineMath: [['$', '$'], ['\\(', '\\)']],
displayMath: [['$$', '$$']]
},
options: {
ignoreHtmlClass: 'tex2jax_ignore',
processHtmlClass: 'tex2jax_process'
},
chtml: { scale: 1.05 }
};
</script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js"></script>
<style>
:root {
--primary: #2c3e50;
--secondary: #34495e;
--accent: #2980b9;
--light: #ecf0f1;
--danger: #c0392b;
--success: #27ae60;
--font-main: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
body {
font-family: var(--font-main);
margin: 0; padding: 0;
background-color: #f4f7f6;
color: #333;
display: flex; height: 100vh; overflow: hidden;
}
/* Sidebar */
.sidebar {
width: 260px;
background-color: var(--primary);
color: white;
display: flex; flex-direction: column;
padding-top: 20px;
box-shadow: 2px 0 5px rgba(0,0,0,0.1);
z-index: 10;
}
.sidebar h2 { text-align: center; font-size: 1.2rem; margin-bottom: 20px; border-bottom: 1px solid var(--secondary); padding-bottom: 15px; }
.nav-btn {
background: none; border: none; color: #bdc3c7;
padding: 15px 20px; text-align: left; cursor: pointer;
font-size: 0.95rem; transition: 0.3s;
border-left: 4px solid transparent;
}
.nav-btn:hover, .nav-btn.active {
background-color: var(--secondary);
color: white;
border-left-color: var(--accent);
}
/* Main Content */
.main-content {
flex: 1; padding: 30px; overflow-y: auto; position: relative;
}
.tab-content { display: none; animation: fadeIn 0.4s; max-width: 900px; margin: 0 auto; }
.tab-content.active { display: block; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); } }
h1 { color: var(--primary); border-bottom: 2px solid var(--accent); padding-bottom: 10px; }
h3 { color: var(--secondary); margin-top: 25px; border-bottom: 1px dashed #ccc; padding-bottom: 5px; }
.theory-block {
background: white; padding: 20px; border-radius: 8px;
box-shadow: 0 2px 5px rgba(0,0,0,0.05); margin-bottom: 20px;
line-height: 1.6; border-left: 4px solid var(--accent);
}
.demo-block {
background: #fff; padding: 25px; border-radius: 8px;
box-shadow: 0 4px 15px rgba(0,0,0,0.1); margin-bottom: 25px;
border: 1px solid #e0e0e0;
}
/* Controls & Sliders */
.controls {
display: grid; grid-template-columns: 1fr 1fr; gap: 20px;
margin-bottom: 20px; background: #f9f9f9; padding: 20px; border-radius: 8px; border: 1px solid #eee;
}
.control-group {
display: flex; flex-direction: column;
}
label { font-weight: 600; margin-bottom: 5px; color: var(--secondary); }
input[type="range"] {
width: 100%; cursor: pointer; margin: 10px 0;
}
.val-display {
font-family: monospace; color: var(--accent); font-weight: bold; float: right;
}
select { padding: 8px; border: 1px solid #ccc; border-radius: 4px; width: 100%; }
button.action-btn {
padding: 10px 20px; background-color: var(--accent); color: white;
border: none; border-radius: 4px; cursor: pointer; font-weight: bold;
margin-top: 10px; width: 100%;
}
button.action-btn:hover { background-color: #1a5276; }
.result-box {
margin-top: 15px; padding: 15px; background-color: #f8f9fa;
border-radius: 4px; border: 1px solid #dee2e6; font-size: 0.95em;
}
.metric-row { display: flex; justify-content: space-between; margin: 8px 0; border-bottom: 1px dashed #e0e0e0; padding-bottom: 4px;}
.highlight-red { color: var(--danger); font-weight: bold; }
.highlight-green { color: var(--success); font-weight: bold; }
canvas { background: white; width: 100%; border: 1px solid #ccc; }
</style>
</head>
<body>
<div class="sidebar">
<h2>Основні поняття обчислювальної математики</h2>
<button class="nav-btn active" onclick="showTab('errors')">1. Теорія похибок</button>
<button class="nav-btn" onclick="showTab('epsilon')">2. Машинний нуль</button>
<button class="nav-btn" onclick="showTab('convergence')">3. Збіжність</button>
<button class="nav-btn" onclick="showTab('stability')">4. Стійкість</button>
<button class="nav-btn" onclick="showTab('conditioning')">5. Обумовленість</button>
</div>
<div class="main-content">
<div id="tab-errors" class="tab-content active">
<h1>1. Теорія похибок</h1>
<div class="theory-block">
<p><strong>Похибка функції від похибок аргументів (Linear Error Propagation):</strong></p>
<p>Якщо $y = f(x)$, а $x$ відоме з похибкою $\Delta x$, то абсолютна похибка функції:</p>
$$ \Delta y \approx |f'(x)| \cdot \Delta x $$
<p>Для нашого прикладу $S = \pi R^2$, похідна $S' = 2\pi R$. Отже, $\Delta S \approx 2\pi R \cdot \Delta R$.</p>
<h3>Похибка функції від похибок декількох аргументів</h3>
<p>Якщо $y = f(x_1, x_2, \ldots, x_n)$, то похибка функції залежить від похибок її аргументів:</p>
<div class="formula">
$$ \Delta y \approx \left| \frac{\partial f}{\partial x_1} \right| \Delta x_1 + \left| \frac{\partial f}{\partial x_2} \right| \Delta x_2 + \ldots + \left| \frac{\partial f}{\partial x_n} \right| \Delta x_n $$
</div>
<p>Для відносної похибки:</p>
<div class="formula">
$$ \delta y \approx \left| \frac{\partial \ln f}{\partial x_1} \right| \Delta x_1 + \left| \frac{\partial \ln f}{\partial x_2} \right| \Delta x_2 + \ldots + \left| \frac{\partial \ln f}{\partial x_n} \right| \Delta x_n $$
</div>
</div>
<div class="demo-block">
<h3>Інтерактив: Площа круга</h3>
<div class="controls">
<div class="control-group">
<label>Радіус $R$: <span id="val-r" class="val-display">10</span></label>
<input type="range" id="rng-r" min="1" max="50" step="0.5" value="10">
</div>
<div class="control-group">
<label>Похибка $\Delta R$: <span id="val-dr" class="val-display">0.5</span></label>
<input type="range" id="rng-dr" min="0.01" max="2.0" step="0.01" value="0.5">
</div>
</div>
<div class="result-box" id="err-output"></div>
<div id="error-plot" style="width:100%; height:250px;"></div>
</div>
</div>
<div id="tab-epsilon" class="tab-content">
<h1>2. Машинна арифметика</h1>
<div class="theory-block">
<p>Комп'ютери мають обмежену точність (IEEE 754 Double Precision). Це призводить до ситуацій, коли математично правильні вирази дають нуль.</p>
</div>
<div class="demo-block">
<h3>Парадокс зникнення: $1 + 10^{-20}$</h3>
<p><strong>Частина 1. Просте додавання:</strong> $(1 + 10^{-20}) - 1$.<br>
В математиці результат $10^{-20}$. Але комп'ютер має лише ~16 значущих цифр.</p>
<button class="action-btn" onclick="runEpsCalc()">Обчислити: (1 + 1e-20) - 1</button>
<div id="eps-calc-res" class="result-box" style="display:none; margin-bottom: 20px;"></div>
<hr style="border: 0; border-top: 1px dashed #ccc; margin: 20px 0;">
<p><strong>Частина 2. Піднесення до степеня:</strong> $(1 + 10^{-20})^k$.<br>
Якщо ми хочемо обчислити складний відсоток або зростання за $k$ кроків, прямий метод дасть помилку. <br>
<em>Рішення:</em> Використати формулу $(1+x)^k \approx 1 + kx$ (Це називається розкладання в степеневий ряд, у даному випадку достатньо лінійного наближення до степеня 1 - апроксимація лінійною функцією).</p>
<div class="controls">
<div class="control-group" style="grid-column: span 2;">
<label>Кількість кроків $k$ (Степінь): <span id="val-pow-k" class="val-display">10^15</span></label>
<input type="range" id="rng-pow-k" min="10" max="18" step="0.1" value="15">
</div>
<button class="action-btn" onclick="runPowerParadox()">Порівняти методи</button>
</div>
<div class="result-box" id="pow-calc-res" style="display:none"></div>
</div>
<div class="demo-block">
<h3>Пошук машинного епсилона</h3>
<p>Цикл ділення на 2, доки $1.0 + \varepsilon > 1.0$.</p>
<button class="action-btn" onclick="findEpsilon()">Запустити алгоритм</button>
<div class="result-box" id="eps-output"></div>
</div>
</div>
<div id="tab-convergence" class="tab-content">
<h1>3. Збіжність ітерацій</h1>
<div class="theory-block">
<p>Метод простих ітерацій $x_{k+1} = \varphi(x_k)$. Змінюйте точку старту та функцію, щоб побачити "сходи", "спіраль" або "хаос".</p>
</div>
<div class="demo-block">
<div class="controls">
<div class="control-group" style="grid-column: span 2;">
<label>Функція $\varphi(x)$:</label>
<select id="conv-func" onchange="drawCobweb()">
<option value="Math.cos(x)">cos(x) (Стійка спіраль)</option>
<option value="1.5 + 0.5*Math.sin(x)">1.5 + 0.5sin(x) (Повільна збіжність)</option>
<option value="2 * x - 2">2x - 2 (Розбіжність)</option>
<option value="3.9 * x * (1 - x)">3.9x(1-x) (Хаос/Логістична)</option>
</select>
</div>
<div class="control-group" style="grid-column: span 2;">
<label>Стартова точка $x_0$: <span id="val-x0" class="val-display">0.1</span></label>
<input type="range" id="rng-x0" min="-1" max="2" step="0.05" value="0.1">
</div>
</div>
<div id="cobweb-plot" style="height:400px;"></div>
</div>
</div>
<div id="tab-stability" class="tab-content">
<h1>4. Стійкість: Класичний приклад</h1>
<div class="theory-block">
<p>Задача: обчислити $y = \sqrt{x+1} - \sqrt{x}$ при дуже великих $x$.</p>
<ul>
<li><strong>Наївний метод:</strong> Віднімання двох близьких чисел. Відбувається <em>катастрофічна втрата значущих цифр</em>.</li>
<li><strong>Раціоналізація (домноження на спряжене):</strong>
$$ \sqrt{x+1} - \sqrt{x} = \frac{(\sqrt{x+1} - \sqrt{x})(\sqrt{x+1} + \sqrt{x})}{\sqrt{x+1} + \sqrt{x}} = \frac{1}{\sqrt{x+1} + \sqrt{x}} $$
Ця формула стійка, бо містить лише додавання додатних чисел.</li>
</ul>
</div>
<div class="demo-block">
<h3>Експеримент: Зростання $x$</h3>
<p>Тягніть слайдер вправо, щоб збільшити степінь $x$ (від $10^1$ до $10^{16}$).</p>
<div class="controls">
<div class="control-group" style="grid-column: span 2;">
<label>Степінь $k$ ($x = 10^k$): <span id="val-stab-k" class="val-display">x = 10^1</span></label>
<input type="range" id="rng-stab-k" min="1" max="16.5" step="0.1" value="5">
</div>
</div>
<div class="result-box" id="stab-results">
</div>
</div>
</div>
<div id="tab-conditioning" class="tab-content">
<h1>5. Обумовленість (Conditioning)</h1>
<div class="theory-block">
<p><strong>Число обумовленості ($\kappa$)</strong> показує чутливість задачі до збурень. $\kappa \approx \frac{\delta_{out}}{\delta_{in}}$.</p>
<p>Графічно: перетин двох прямих (ааналітично - розв'язок лінійної системи рівнянь). Якщо прямі майже паралельні (кажуть "задача погано обумовлена"), найменший зсув однієї прямої призводить до гігантського зсуву точки перетину.</p>
</div>
<div class="demo-block">
<div class="controls">
<div class="control-group" style="grid-column: span 2;">
<label>Кут нахилу червоної прямої (збурення): <span id="val-cond" class="val-display">0.900</span></label>
<input type="range" id="rng-cond" min="0.8" max="1.15" step="0.001" value="0.9">
</div>
</div>
<canvas id="cond-canvas" width="600" height="350"></canvas>
<div class="result-box">
<div class="metric-row">
<span>Вхідне збурення ($\delta_{in}$):</span>
<span id="res-d-in">0%</span>
</div>
<div class="metric-row">
<span>Вихідна похибка ($\delta_{out}$):</span>
<span id="res-d-out" class="highlight-red">0%</span>
</div>
<div class="metric-row" style="border:none; margin-top:10px;">
<span>Число обумовленості ($\kappa$):</span>
<span id="res-cond-num" style="background:var(--secondary); color:white; padding:2px 5px; border-radius:3px;">1</span>
</div>
</div>
</div>
</div>
</div>
<script>
// --- UTILS & NAVIGATION ---
function showTab(id) {
document.querySelectorAll('.tab-content').forEach(d => d.classList.remove('active'));
document.querySelectorAll('.nav-btn').forEach(b => b.classList.remove('active'));
document.getElementById('tab-'+id).classList.add('active');
// Button highlighting hack
const map = ['errors', 'epsilon', 'convergence', 'stability', 'conditioning'];
const btns = document.querySelectorAll('.nav-btn');
if(btns[map.indexOf(id)]) btns[map.indexOf(id)].classList.add('active');
// Refresh specific visualizers
if(id === 'convergence') drawCobweb();
if(id === 'stability') updateStability();
if(id === 'conditioning') updateConditioning();
}
// ==========================================
// 1. ERRORS LOGIC (ВИПРАВЛЕНО)
// ==========================================
const rngR = document.getElementById('rng-r');
const rngdR = document.getElementById('rng-dr');
function updateErrors() {
const R = parseFloat(rngR.value);
const dR = parseFloat(rngdR.value);
// Оновлення текстових значень
document.getElementById('val-r').innerText = R.toFixed(1);
document.getElementById('val-dr').innerText = dR.toFixed(2);
const S = Math.PI * R * R;
// Лінійна оцінка похибки: dS = |f'(R)| * dR = 2 * pi * R * dR
const dS = 2 * Math.PI * R * dR;
const rel_R = (dR / R) * 100;
const rel_S = (dS / S) * 100;
// Виведення тексту
document.getElementById('err-output').innerHTML = `
<div class="metric-row"><strong>Аргумент (Радіус):</strong> $R = ${R} \\pm ${dR}$ <span style="color:blue">($\\delta \\approx ${rel_R.toFixed(2)}\\%$)</span></div>
<div class="metric-row"><strong>Функція (Площа):</strong> $S \\approx ${S.toFixed(1)} \\pm ${dS.toFixed(1)}$ <span style="color:red">($\\delta \\approx ${rel_S.toFixed(2)}\\%$)</span></div>
`;
if(window.MathJax) MathJax.typesetPromise();
// --- ГРАФІК ---
// Розрахуємо межі для осі X, щоб графік не стрибав,
// але при цьому вміщував максимальну можливу похибку для поточного R.
// Максимальна похибка на слайдері - 2.0. Тому dS_max ~ 2 * pi * R * 2.0
const max_possible_dS = 2 * Math.PI * R * 2.0;
const xRange = [S - max_possible_dS * 1.1, S + max_possible_dS * 1.1];
const traceLine = {
x: [S-dS, S+dS],
y: [0,0],
mode: 'lines+markers',
line: {color:'#e74c3c', width:8},
marker: {size: 10, symbol: 'line-ns-open', color: '#e74c3c'},
name: 'Інтервал похибки',
hoverinfo: 'x'
};
const traceCenter = {
x: [S],
y: [0],
mode: 'markers',
marker: {size:16, color:'#2c3e50'},
name: 'Точне S',
hoverinfo: 'x'
};
const layout = {
title: 'Візуалізація інтервалу невизначеності',
xaxis: {
title: 'Площа',
range: xRange, // Фіксуємо діапазон відносно макс. можливої похибки
zeroline: false
},
yaxis: {
showticklabels:false,
range:[-0.5, 0.5],
fixedrange: true
},
height: 250,
margin: {t:40, b:40, l:40, r:40},
showlegend: false,
annotations: [
{x: S, y: 0.15, text: "S", showarrow: false, font: {size: 14, color: '#2c3e50'}},
{x: S-dS, y: -0.15, text: (S-dS).toFixed(0), showarrow: false, font: {size: 10, color: '#e74c3c'}},
{x: S+dS, y: -0.15, text: (S+dS).toFixed(0), showarrow: false, font: {size: 10, color: '#e74c3c'}}
]
};
Plotly.react('error-plot', [traceLine, traceCenter], layout, {displayModeBar: false});
}
rngR.addEventListener('input', updateErrors);
rngdR.addEventListener('input', updateErrors);
// ==========================================
// 2. EPSILON LOGIC
// ==========================================
function runEpsCalc() {
const res = (1.0 + 1e-20) - 1.0;
const div = document.getElementById('eps-calc-res');
div.style.display = 'block';
div.innerHTML = `
Результат JS: <strong>${res}</strong><br>
Очікувано математично: <strong>1e-20</strong><br>
<span style="color:red; font-size:0.9em">Причина: 1e-20 менше ніж машинний епсилон відносно одиниці.</span>
`;
}
// --- Додати це в блоці JS (Секція 2. EPSILON) ---
const rngPowK = document.getElementById('rng-pow-k');
// Слухач для оновлення відображення числа над слайдером
rngPowK.addEventListener('input', function() {
const k_exp = parseFloat(rngPowK.value);
document.getElementById('val-pow-k').innerHTML = `10^{${k_exp.toFixed(1)}}`;
if(window.MathJax) MathJax.typesetPromise();
runPowerParadox(); // Автоматичний перерахунок при русі
});
function runPowerParadox() {
const k_exp = parseFloat(rngPowK.value);
const k = Math.pow(10, k_exp); // Наприклад, 10^15
const eps = 1e-20;
// 1. Наївний метод JS
// Спочатку виконується (1 + eps), що стає рівним 1.0 через втрату точності
// Потім 1.0 підноситься до степеня k, що дорівнює 1.0
const naive = Math.pow(1 + eps, k);
// 2. Математично коректний підхід для малих чисел
// Використовуємо біноміальне наближення: (1+x)^k ≈ 1 + kx
// Це працює, бо k*eps значно більше за машинний епсилон, хоча саме eps - ні.
const smart_increment = k * eps;
const smart = 1 + smart_increment;
const div = document.getElementById('pow-calc-res');
div.style.display = 'block';
div.innerHTML = `
<div class="metric-row">
<span>Степінь $k$:</span>
<span>$10^{${k_exp.toFixed(1)}}$</span>
</div>
<div class="metric-row" style="color: var(--danger);">
<span>Наївний JS (Math.pow):</span>
<span>${naive.toFixed(1)}</span>
</div>
<div class="metric-row" style="color: var(--success); font-weight:bold;">
<span>Формула ($1+kx$):</span>
<span>${smart.toFixed(10)}...</span>
</div>
<p style="font-size:0.9em; margin-top:10px; color:#555;">
<strong>Пояснення:</strong> У наївному методі комп'ютер губить $10^{-20}$ ще до піднесення у степінь. Тому відповідь завжди не правильна - одиниця.
У формулі ми спочатку множимо $k \\cdot 10^{-20} = 10^{${(k_exp-20).toFixed(1)}}$, що є "помітним" числом для комп'ютера, і лише потім додаємо до 1.
</p>
`;
if(window.MathJax) MathJax.typesetPromise();
}
function findEpsilon() {
let eps = 1.0;
let iter = 0;
let html = "<table style='width:100%; border-collapse:collapse; font-size:0.9em;'><tr><th>Крок</th><th>Epsilon</th><th>1+Eps > 1?</th></tr>";
while (1.0 + eps/2.0 !== 1.0) {
eps /= 2.0;
iter++;
if(iter < 6 || iter > 49) {
html += `<tr><td style="border:1px solid #ddd; padding:4px;">${iter}</td><td>${eps.toExponential(4)}</td><td style="color:green">Так</td></tr>`;
} else if (iter === 6) html += "<tr><td colspan='3'>...</td></tr>";
}
html += `<tr style="background:#ffdada"><td><strong>${iter}</strong></td><td><strong>${(eps/2).toExponential(4)}</strong></td><td style="color:red; font-weight:bold;">НІ (Межу знайдено)</td></tr></table>`;
document.getElementById('eps-output').innerHTML = html;
}
// ==========================================
// 3. CONVERGENCE LOGIC
// ==========================================
const rngX0 = document.getElementById('rng-x0');
function drawCobweb() {
const expr = document.getElementById('conv-func').value;
const x0 = parseFloat(rngX0.value);
document.getElementById('val-x0').innerText = x0.toFixed(2);
const f = (x) => {
try { return eval(expr.replace(/x/g, `(${x})`)); } catch { return 0; }
};
let x = [], y = [];
let curr = x0;
x.push(curr); y.push(0);
for(let i=0; i<40; i++) {
let next = f(curr);
if(Math.abs(next) > 100) break; // limit divergence
x.push(curr); y.push(next);
x.push(next); y.push(next);
curr = next;
}
// Plot Background functions
const domain = []; const f_vals = []; const identity = [];
for(let i=-2; i<=3; i+=0.1) {
domain.push(i); f_vals.push(f(i)); identity.push(i);
}
Plotly.react('cobweb-plot', [
{x: domain, y: f_vals, type:'scatter', name:'y=φ(x)', line:{color:'#2980b9'}},
{x: domain, y: identity, type:'scatter', name:'y=x', line:{dash:'dot', color:'gray'}},
{x: x, y: y, type:'scatter', mode:'lines+markers', name:'Ітерації', line:{color:'#e74c3c', width:1}, marker:{size:4}}
], { margin: {t:20, b:20}, height: 400, hovermode:'closest' });
}
rngX0.addEventListener('input', drawCobweb);
// ==========================================
// 4. STABILITY LOGIC (SQRT EXAMPLE)
// ==========================================
const rngStab = document.getElementById('rng-stab-k');
function updateStability() {
const k = parseFloat(rngStab.value);
const x = Math.pow(10, k);
document.getElementById('val-stab-k').innerHTML = `x = 10^{${k.toFixed(1)}}`;
if(window.MathJax) MathJax.typesetPromise();
// 1. Naive calculation
const naive = Math.sqrt(x + 1) - Math.sqrt(x);
// 2. Rationalized calculation (Assume "True" for comparison)
const rational = 1.0 / (Math.sqrt(x + 1) + Math.sqrt(x));
// Calculate discrepancy
// Note: For extremely large x, naive becomes exactly 0.
let diff = Math.abs(naive - rational);
let errorPercent = (rational !== 0) ? (diff / rational) * 100 : 0;
let naiveStr = naive.toExponential(10);
let ratStr = rational.toExponential(10);
// Coloring for bad results
let colorStyle = "color: black;";
if (errorPercent > 10) colorStyle = "color: var(--danger); font-weight:bold;";
else if (errorPercent > 0.00001) colorStyle = "color: orange;";
document.getElementById('stab-results').innerHTML = `
<div class="metric-row">
<span>Значення $x$:</span>
<span>${x.toExponential(2)}</span>
</div>
<div class="metric-row" style="${colorStyle}">
<span>Наївний:</span>
<span>${naiveStr}</span>
</div>
<div class="metric-row" style="color:var(--success); font-weight:bold;">
<span>Раціоналізований:</span>
<span>${ratStr}</span>
</div>
<div style="margin-top:10px; border-top:1px solid #ccc; padding-top:5px;">
Відносна похибка наївного методу: <span style="${colorStyle}">${errorPercent.toFixed(4)}%</span>
</div>
<p style="font-size:0.8em; color:#666; margin-top:5px">
${k > 15.5 ? "Увага! При $x > 10^{16}$ наївний результат стає рівним 0, тобто 100% похибки!" : "Спостерігайте, як при збільшенні $x$ точність падає."}
</p>
`;
if(window.MathJax) MathJax.typesetPromise();
}
rngStab.addEventListener('input', updateStability);
// ==========================================
// 5. CONDITIONING LOGIC
// ==========================================
const rngCond = document.getElementById('rng-cond');
const cvs = document.getElementById('cond-canvas');
const ctx = cvs.getContext('2d');
const k_base = 0.9;
const x_base = 10;
function updateConditioning() {
const k_curr = parseFloat(rngCond.value);
document.getElementById('val-cond').innerText = k_curr.toFixed(3);
let x_new = 1 / (1 - k_curr);
if(!isFinite(x_new)) x_new = 1000;
let rel_err_in = Math.abs((k_curr - k_base) / k_base) * 100;
let rel_err_out = Math.abs((x_new - x_base) / x_base) * 100;
let kappa = (rel_err_in === 0) ? 1 : (rel_err_out / rel_err_in);
document.getElementById('res-d-in').innerText = rel_err_in.toFixed(2) + "%";
document.getElementById('res-d-out').innerText = rel_err_out.toFixed(2) + "%";
document.getElementById('res-cond-num').innerText = kappa > 100 ? "> 100" : kappa.toFixed(1);
// Draw
const w = cvs.width, h = cvs.height;
ctx.clearRect(0,0,w,h);
const scale = 20;
const tx = (x) => w/2 + (x - x_base) * scale;
const ty = (y) => h/2 - (y - x_base) * scale;
// Axes
ctx.strokeStyle = "#eee"; ctx.beginPath();
ctx.moveTo(0, h/2); ctx.lineTo(w, h/2);
ctx.moveTo(w/2, 0); ctx.lineTo(w/2, h);
ctx.stroke();
// Lines
ctx.strokeStyle = "blue"; ctx.lineWidth = 2; ctx.beginPath();
ctx.moveTo(tx(-10), ty(-10)); ctx.lineTo(tx(30), ty(30)); ctx.stroke();
ctx.strokeStyle = "red"; ctx.lineWidth = 2; ctx.beginPath();
ctx.moveTo(tx(0), ty(1)); ctx.lineTo(tx(30), ty(30*k_curr + 1)); ctx.stroke();
// Points
ctx.fillStyle = "#ccc"; ctx.beginPath(); ctx.arc(tx(x_base), ty(x_base), 4, 0, Math.PI*2); ctx.fill();
if(Math.abs(x_new - x_base) < 15) {
ctx.fillStyle = "black"; ctx.beginPath(); ctx.arc(tx(x_new), ty(x_new), 5, 0, Math.PI*2); ctx.fill();
// Arrow
ctx.strokeStyle = "green"; ctx.lineWidth = 2; ctx.beginPath();
ctx.moveTo(tx(x_base), ty(x_base) + 15);
ctx.lineTo(tx(x_new), ty(x_base) + 15);
ctx.stroke();
}
}
rngCond.addEventListener('input', updateConditioning);
// Initial Calls
updateErrors();
updateStability();
</script>
</body>
</html>