Repository Public
1/*2 * SP CLIP scene kit — noyau numérique `SKN` (aucune dépendance, aucun accès au DOM, IIFE compatible ES5).3 * Chargé dans la page d'une scène (global `SKN`) ET importé tel quel par vitest sous Node (attaché à `globalThis`).4 *5 * Règle d'or : une visualisation scientifique ou financière ne dessine QUE des nombres calculés ici, jamais des valeurs6 * improvisées. Tout est pur et déterministe : ni générateur aléatoire global ni horloge ; l'aléa passe par `SKN.rng(seed)`.7 *8 * Toute fonction qui PRODUIT un jeu de données renvoie des tableaux/objets simples plus9 * meta = { kind: "computed", model, params, formula (LaTeX de la définition) [, note] }10 * pour que la scène étiquette honnêtement le visuel comme un calcul de modèle (et non des données de marché observées).11 * Les fonctions scalaires (pdf, VAN, …) et les transformations (cumsum, ohlcFromPath, rollingVolatility) renvoient12 * directement un nombre ou un tableau. Toute entrée absurde lève une Error explicite (« SKN.<fonction>: … »).13 *14 * Conventions : angles en radians ; taux et volatilités en décimal (0.05 = 5 %) ; matrices = tableaux de lignes ;15 * variance/écart-type/covariance = estimateurs d'échantillon (diviseur n−1) sauf `population = true`.16 *17 * Approximations (toutes vérifiées dans tests/numerics.test.ts) :18 * erf/erfc série à termes positifs (|x| < 2) + fraction continue de erfc (|x| ≥ 2) : erreur absolue < 1e-14,19 * erreur relative de la queue de normalCdf < 1e-11 jusqu'à −8 écarts-types.20 * normalInv approximation rationnelle d'Acklam (erreur relative 1,15e-9) puis 3 pas de Halley : |erreur| < 1e-12.21 * logGamma Lanczos (g = 7, 9 coefficients) : erreur relative < 1e-13 (sert à studentTPdf, binomialPmf, poissonPmf).22 * integrate Simpson composite, erreur O(h^4) ; derivative : différence centrée, erreur O(h^2).23 * rk4 O(dt^4), euler O(dt) ; nBodyStep : Verlet vitesse O(dt^2) symplectique ; wave1d/heat1d : différences finies24 * explicites O(dt, dx^2) avec condition de stabilité vérifiée (sinon Error).25 */26(function () {27 "use strict";28 var root = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this;29 var PI = Math.PI, SQRT2 = Math.SQRT2, SQRT2PI = Math.sqrt(2 * Math.PI);3031 /* ── validation ── */32 function fail(fn, msg) { throw new Error("SKN." + fn + ": " + msg); }33 function isNum(x) { return typeof x === "number" && isFinite(x); }34 function num(fn, x, name) { if (!isNum(x)) fail(fn, name + " must be a finite number"); return x; }35 function pos(fn, x, name) { if (!isNum(x) || x <= 0) fail(fn, name + " must be > 0"); return x; }36 function nonneg(fn, x, name) { if (!isNum(x) || x < 0) fail(fn, name + " must be >= 0"); return x; }37 function int(fn, x, name, min) { if (!isNum(x) || Math.floor(x) !== x || x < (min == null ? 0 : min)) fail(fn, name + " must be an integer >= " + (min == null ? 0 : min)); return x; }38 function vec(fn, a, name, minLen) {39 if (!Array.isArray(a) || a.length < (minLen == null ? 1 : minLen)) fail(fn, name + " must be an array of at least " + (minLen == null ? 1 : minLen) + " number(s)");40 for (var i = 0; i < a.length; i++) if (!isNum(a[i])) fail(fn, name + "[" + i + "] must be a finite number");41 return a;42 }43 function mat(fn, A, name) {44 if (!Array.isArray(A) || !A.length || !Array.isArray(A[0]) || !A[0].length) fail(fn, name + " must be a non-empty matrix (array of rows)");45 for (var i = 0; i < A.length; i++) { if (!Array.isArray(A[i]) || A[i].length !== A[0].length) fail(fn, name + " must be rectangular"); vec(fn, A[i], name + "[" + i + "]"); }46 return A;47 }48 function square(fn, A, name) { mat(fn, A, name); if (A.length !== A[0].length) fail(fn, name + " must be square"); return A; }49 function def(x, d) { return x == null ? d : x; }50 function meta(model, params, formula, note) { var m = { kind: "computed", model: model, params: params, formula: formula }; if (note) m.note = note; return m; }5152 /* ── aléa : mulberry32 (période 2^32) ; normal() par Box–Muller ── */53 function rng(seed) {54 var a = int("rng", def(seed, 1), "seed", -2147483648) | 0, spare = null;55 function next() {56 a = (a + 0x6D2B79F5) | 0;57 var t = Math.imul(a ^ (a >>> 15), 1 | a);58 t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;59 return ((t ^ (t >>> 14)) >>> 0) / 4294967296;60 }61 return {62 next: next,63 normal: function () {64 if (spare != null) { var s = spare; spare = null; return s; }65 var r = Math.sqrt(-2 * Math.log(1 - next())), th = 2 * PI * next();66 spare = r * Math.sin(th);67 return r * Math.cos(th);68 },69 int: function (n) { int("rng.int", n, "n", 1); return Math.floor(next() * n); }70 };71 }7273 /* ── base ── */74 function linspace(a, b, n) {75 num("linspace", a, "a"); num("linspace", b, "b"); int("linspace", n, "n", 1);76 if (n === 1) return [a];77 var out = new Array(n);78 for (var i = 0; i < n; i++) out[i] = a + (b - a) * i / (n - 1);79 out[n - 1] = b;80 return out;81 }82 function range(a, b, step) {83 if (b == null) { b = a; a = 0; }84 step = def(step, 1); num("range", a, "start"); num("range", b, "end"); num("range", step, "step");85 if (step === 0) fail("range", "step must not be 0");86 var out = [], n = Math.max(0, Math.ceil((b - a) / step - 1e-12));87 for (var i = 0; i < n; i++) out.push(a + i * step);88 return out;89 }90 function clamp(x, lo, hi) { return Math.min(hi, Math.max(lo, x)); }91 function lerp(a, b, t) { return a + (b - a) * t; }92 function sum(xs) { vec("sum", xs, "xs", 0); var s = 0; for (var i = 0; i < xs.length; i++) s += xs[i]; return s; }93 function mean(xs) { vec("mean", xs, "xs"); return sum(xs) / xs.length; }94 function variance(xs, population) {95 vec("variance", xs, "xs", population ? 1 : 2);96 var m = mean(xs), s = 0;97 for (var i = 0; i < xs.length; i++) s += (xs[i] - m) * (xs[i] - m);98 return s / (population ? xs.length : xs.length - 1);99 }100 function std(xs, population) { return Math.sqrt(variance(xs, population)); }101 function covariance(xs, ys, population) {102 vec("covariance", xs, "xs", 2); vec("covariance", ys, "ys", 2);103 if (xs.length !== ys.length) fail("covariance", "xs and ys must have the same length");104 var mx = mean(xs), my = mean(ys), s = 0;105 for (var i = 0; i < xs.length; i++) s += (xs[i] - mx) * (ys[i] - my);106 return s / (population ? xs.length : xs.length - 1);107 }108 function correlation(xs, ys) {109 var sx = std(xs), sy = std(ys);110 if (sx === 0 || sy === 0) fail("correlation", "a constant series has no correlation");111 return covariance(xs, ys) / (sx * sy);112 }113 /* quantile par interpolation linéaire (type 7 de Hyndman–Fan, celui de R et NumPy par défaut) */114 function quantile(xs, p) {115 vec("quantile", xs, "xs"); num("quantile", p, "p");116 if (p < 0 || p > 1) fail("quantile", "p must be in [0, 1]");117 var s = xs.slice().sort(function (a, b) { return a - b; }), h = (s.length - 1) * p, lo = Math.floor(h), hi = Math.ceil(h);118 return s[lo] + (s[hi] - s[lo]) * (h - lo);119 }120 function histogram(xs, bins) {121 vec("histogram", xs, "xs"); int("histogram", bins, "bins", 1);122 var lo = Math.min.apply(null, xs), hi = Math.max.apply(null, xs);123 if (lo === hi) { lo -= 0.5; hi += 0.5; }124 var w = (hi - lo) / bins, counts = [], i;125 for (i = 0; i < bins; i++) counts.push(0);126 for (i = 0; i < xs.length; i++) counts[Math.min(bins - 1, Math.floor((xs[i] - lo) / w))]++;127 return { edges: linspace(lo, hi, bins + 1), counts: counts, density: counts.map(function (c) { return c / (xs.length * w); }), min: lo, max: hi, width: w };128 }129 function cumsum(xs) { vec("cumsum", xs, "xs", 0); var s = 0; return xs.map(function (x) { s += x; return s; }); }130 function dot(a, b) {131 if (a.length !== b.length) fail("dot", "vectors must have the same length");132 var s = 0; for (var i = 0; i < a.length; i++) s += a[i] * b[i]; return s;133 }134135 /* ── matrices (tableaux de lignes) ── */136 function transpose(A) { mat("transpose", A, "A"); return A[0].map(function (_, j) { return A.map(function (r) { return r[j]; }); }); }137 function matmul(A, B) {138 mat("matmul", A, "A"); mat("matmul", B, "B");139 if (A[0].length !== B.length) fail("matmul", "incompatible shapes " + A.length + "x" + A[0].length + " and " + B.length + "x" + B[0].length);140 return A.map(function (r) { return B[0].map(function (_, j) { var s = 0; for (var k = 0; k < B.length; k++) s += r[k] * B[k][j]; return s; }); });141 }142 function matvec(A, v) {143 mat("matvec", A, "A"); vec("matvec", v, "v");144 if (A[0].length !== v.length) fail("matvec", "incompatible shapes");145 return A.map(function (r) { return dot(r, v); });146 }147 function identity(n) { var I = []; for (var i = 0; i < n; i++) { I.push([]); for (var j = 0; j < n; j++) I[i].push(i === j ? 1 : 0); } return I; }148 /* élimination de Gauss à pivot partiel sur [A | B] ; B = matrice n×m de seconds membres */149 function gauss(fn, A, B) {150 var n = A.length, M = A.map(function (r, i) { return r.concat(B[i]); }), w = M[0].length, i, j, k;151 var scale = 0;152 for (i = 0; i < n; i++) for (j = 0; j < n; j++) scale = Math.max(scale, Math.abs(A[i][j]));153 for (k = 0; k < n; k++) {154 var p = k;155 for (i = k + 1; i < n; i++) if (Math.abs(M[i][k]) > Math.abs(M[p][k])) p = i;156 if (Math.abs(M[p][k]) <= 1e-13 * scale) fail(fn, "matrix is singular (or numerically so)");157 var tmp = M[k]; M[k] = M[p]; M[p] = tmp;158 for (i = k + 1; i < n; i++) { var f = M[i][k] / M[k][k]; if (f !== 0) for (j = k; j < w; j++) M[i][j] -= f * M[k][j]; }159 }160 var X = [];161 for (i = 0; i < n; i++) X.push(new Array(w - n));162 for (var c = n; c < w; c++) for (i = n - 1; i >= 0; i--) {163 var s = M[i][c];164 for (j = i + 1; j < n; j++) s -= M[i][j] * X[j][c - n];165 X[i][c - n] = s / M[i][i];166 }167 return X;168 }169 function solve(A, b) {170 square("solve", A, "A"); vec("solve", b, "b");171 if (b.length !== A.length) fail("solve", "b must have " + A.length + " entries");172 return gauss("solve", A, b.map(function (x) { return [x]; })).map(function (r) { return r[0]; });173 }174 function inverse(A) { square("inverse", A, "A"); return gauss("inverse", A, identity(A.length)); }175 /* Cholesky A = L·Lᵀ (L triangulaire inférieure) ; lève une erreur si A n'est pas symétrique définie positive */176 function cholesky(A) {177 square("cholesky", A, "A");178 var n = A.length, L = [], i, j, k;179 for (i = 0; i < n; i++) { L.push([]); for (j = 0; j < n; j++) L[i].push(0); }180 for (i = 0; i < n; i++) for (j = 0; j <= i; j++) {181 if (Math.abs(A[i][j] - A[j][i]) > 1e-10 * (Math.abs(A[i][j]) + Math.abs(A[j][i]) + 1e-300)) fail("cholesky", "matrix is not symmetric");182 var s = A[i][j];183 for (k = 0; k < j; k++) s -= L[i][k] * L[j][k];184 if (i === j) { if (!(s > 1e-14 * Math.abs(A[i][i]))) fail("cholesky", "matrix is not positive definite"); L[i][i] = Math.sqrt(s); }185 else L[i][j] = s / L[j][j];186 }187 return L;188 }189190 /* ── fonctions spéciales ── */191 function erf(x) {192 num("erf", x, "x");193 if (x < 0) return -erf(-x);194 if (x >= 2) return 1 - erfc(x);195 // erf(x) = 2/√π · e^{−x²} · Σ 2ⁿ x^{2n+1} / (2n+1)!! (termes tous positifs : aucune annulation)196 var term = x, s = x;197 for (var n = 1; n < 200 && term > 1e-17 * s; n++) { term *= 2 * x * x / (2 * n + 1); s += term; }198 return 2 / Math.sqrt(PI) * Math.exp(-x * x) * s;199 }200 function erfc(x) {201 num("erfc", x, "x");202 if (x < 0) return 2 - erfc(-x);203 if (x < 2) return 1 - erf(x);204 // fraction continue erfc(x) = e^{−x²}/√π · 1/(x + (1/2)/(x + (2/2)/(x + (3/2)/(x + …)))), évaluée à rebours205 var f = x;206 for (var k = 120; k >= 1; k--) f = x + (k / 2) / f;207 return Math.exp(-x * x) / (Math.sqrt(PI) * f);208 }209 var LANCZOS = [0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7];210 function logGamma(x) {211 pos("logGamma", x, "x");212 if (x < 0.5) return Math.log(PI / Math.sin(PI * x)) - logGamma(1 - x);213 x -= 1;214 var a = LANCZOS[0], t = x + 7.5;215 for (var i = 1; i < 9; i++) a += LANCZOS[i] / (x + i);216 return 0.5 * Math.log(2 * PI) + (x + 0.5) * Math.log(t) - t + Math.log(a);217 }218219 /* ── probabilités ── */220 function normalPdf(x, mu, sd) { mu = def(mu, 0); sd = pos("normalPdf", def(sd, 1), "sd"); var z = (num("normalPdf", x, "x") - mu) / sd; return Math.exp(-0.5 * z * z) / (sd * SQRT2PI); }221 function normalCdf(x, mu, sd) { mu = def(mu, 0); sd = pos("normalCdf", def(sd, 1), "sd"); return 0.5 * erfc(-(num("normalCdf", x, "x") - mu) / (sd * SQRT2)); }222 var AK_A = [-3.969683028665376e+01, 2.209460984245205e+02, -2.759285104469687e+02, 1.383577518672690e+02, -3.066479806614716e+01, 2.506628277459239e+00];223 var AK_B = [-5.447609879822406e+01, 1.615858368580409e+02, -1.556989798598866e+02, 6.680131188771972e+01, -1.328068155288572e+01];224 var AK_C = [-7.784894002430293e-03, -3.223964580411365e-01, -2.400758277161838e+00, -2.549732539343734e+00, 4.374664141464968e+00, 2.938163982698783e+00];225 var AK_D = [7.784695709041462e-03, 3.224671290700398e-01, 2.445134137142996e+00, 3.754408661907416e+00];226 function normalInv(p, mu, sd) {227 mu = def(mu, 0); sd = pos("normalInv", def(sd, 1), "sd");228 if (!isNum(p) || p <= 0 || p >= 1) fail("normalInv", "p must be in (0, 1)");229 if (p > 0.5) return mu - sd * normalInv(1 - p); // symétrie : on ne travaille que dans la queue gauche230 var q, r, x;231 if (p < 0.02425) {232 q = Math.sqrt(-2 * Math.log(p));233 x = (((((AK_C[0] * q + AK_C[1]) * q + AK_C[2]) * q + AK_C[3]) * q + AK_C[4]) * q + AK_C[5]) / ((((AK_D[0] * q + AK_D[1]) * q + AK_D[2]) * q + AK_D[3]) * q + 1);234 } else {235 q = p - 0.5; r = q * q;236 x = (((((AK_A[0] * r + AK_A[1]) * r + AK_A[2]) * r + AK_A[3]) * r + AK_A[4]) * r + AK_A[5]) * q / (((((AK_B[0] * r + AK_B[1]) * r + AK_B[2]) * r + AK_B[3]) * r + AK_B[4]) * r + 1);237 }238 for (var i = 0; i < 3; i++) { // raffinement de Halley sur Φ(x) − p239 var e = normalCdf(x) - p, u = e / normalPdf(x);240 x -= u / (1 + x * u / 2);241 }242 return mu + sd * x;243 }244 function lognormalPdf(x, mu, sigma) {245 mu = def(mu, 0); sigma = pos("lognormalPdf", def(sigma, 1), "sigma"); num("lognormalPdf", x, "x");246 if (x <= 0) return 0;247 var z = (Math.log(x) - mu) / sigma;248 return Math.exp(-0.5 * z * z) / (x * sigma * SQRT2PI);249 }250 function studentTPdf(x, nu) {251 num("studentTPdf", x, "x"); pos("studentTPdf", nu, "nu");252 return Math.exp(logGamma((nu + 1) / 2) - logGamma(nu / 2) - 0.5 * Math.log(nu * PI) - (nu + 1) / 2 * Math.log(1 + x * x / nu));253 }254 function uniformPdf(x, a, b) { a = def(a, 0); b = def(b, 1); num("uniformPdf", x, "x"); if (!(b > a)) fail("uniformPdf", "need b > a"); return x >= a && x <= b ? 1 / (b - a) : 0; }255 function exponentialPdf(x, rate) { rate = pos("exponentialPdf", def(rate, 1), "rate"); num("exponentialPdf", x, "x"); return x < 0 ? 0 : rate * Math.exp(-rate * x); }256 function prob(fn, p) { if (!isNum(p) || p < 0 || p > 1) fail(fn, "p must be in [0, 1]"); return p; }257 function binomialPmf(k, n, p) {258 int("binomialPmf", n, "n"); prob("binomialPmf", p); num("binomialPmf", k, "k");259 if (Math.floor(k) !== k || k < 0 || k > n) return 0;260 if (p === 0) return k === 0 ? 1 : 0;261 if (p === 1) return k === n ? 1 : 0;262 return Math.exp(logGamma(n + 1) - logGamma(k + 1) - logGamma(n - k + 1) + k * Math.log(p) + (n - k) * Math.log(1 - p));263 }264 function poissonPmf(k, lambda) {265 pos("poissonPmf", lambda, "lambda"); num("poissonPmf", k, "k");266 if (Math.floor(k) !== k || k < 0) return 0;267 return Math.exp(k * Math.log(lambda) - lambda - logGamma(k + 1));268 }269 /* sample(dist, n, rng) — dist = { type, … } :270 normal {mean=0, sd=1} · lognormal {mu=0, sigma=1} · uniform {a=0, b=1} · exponential {rate=1}271 studentT {nu entier ≥ 1} · binomial {n, p} · poisson {lambda} */272 function sample(dist, n, r) {273 if (!dist || typeof dist.type !== "string") fail("sample", "dist must be an object { type: \"normal\" | \"lognormal\" | \"uniform\" | \"exponential\" | \"studentT\" | \"binomial\" | \"poisson\", ... }");274 int("sample", n, "n"); if (!r || typeof r.next !== "function") fail("sample", "rng must come from SKN.rng(seed)");275 var one, d = dist;276 if (d.type === "normal") { var sd = pos("sample", def(d.sd, 1), "sd"), mu = def(d.mean, 0); one = function () { return mu + sd * r.normal(); }; }277 else if (d.type === "lognormal") { var sg = pos("sample", def(d.sigma, 1), "sigma"), m = def(d.mu, 0); one = function () { return Math.exp(m + sg * r.normal()); }; }278 else if (d.type === "uniform") { var a = def(d.a, 0), b = def(d.b, 1); if (!(b > a)) fail("sample", "need b > a"); one = function () { return a + (b - a) * r.next(); }; }279 else if (d.type === "exponential") { var rate = pos("sample", def(d.rate, 1), "rate"); one = function () { return -Math.log(1 - r.next()) / rate; }; }280 else if (d.type === "studentT") { var nu = int("sample", d.nu, "nu", 1); one = function () { var z = r.normal(), c = 0; for (var i = 0; i < nu; i++) { var g = r.normal(); c += g * g; } return z / Math.sqrt(c / nu); }; }281 else if (d.type === "binomial") { var bn = int("sample", d.n, "n"), bp = prob("sample", d.p); one = function () { var c = 0; for (var i = 0; i < bn; i++) if (r.next() < bp) c++; return c; }; }282 else if (d.type === "poisson") {283 var lam = pos("sample", d.lambda, "lambda"); if (lam > 700) fail("sample", "poisson lambda must be <= 700");284 one = function () { var u = r.next(), k = 0, p = Math.exp(-lam), c = p; while (u > c && k < 1e5) { k++; p *= lam / k; c += p; } return k; }; // inversion séquentielle285 } else fail("sample", "unknown distribution \"" + d.type + "\"");286 var out = new Array(n);287 for (var i = 0; i < n; i++) out[i] = one();288 return out;289 }290291 /* ── analyse, EDO, champs ── */292 function fnArg(fn, f, name) { if (typeof f !== "function") fail(fn, name + " must be a function"); return f; }293 function derivative(f, x, h) {294 fnArg("derivative", f, "f"); num("derivative", x, "x");295 h = pos("derivative", def(h, 1e-5 * Math.max(1, Math.abs(x))), "h");296 return (f(x + h) - f(x - h)) / (2 * h);297 }298 function integrate(f, a, b, n) {299 fnArg("integrate", f, "f"); num("integrate", a, "a"); num("integrate", b, "b");300 n = int("integrate", def(n, 200), "n", 2); if (n % 2) n++;301 var h = (b - a) / n, s = f(a) + f(b);302 for (var i = 1; i < n; i++) s += f(a + i * h) * (i % 2 ? 4 : 2);303 return s * h / 3;304 }305 function axpy(y, a, k) { var o = new Array(y.length); for (var i = 0; i < y.length; i++) o[i] = y[i] + a * k[i]; return o; }306 function odeSolve(fn, order, f, y0, t0, t1, n) {307 fnArg(fn, f, "f"); num(fn, t0, "t0"); num(fn, t1, "t1"); int(fn, n, "n", 1);308 var scalar = typeof y0 === "number", y = scalar ? [num(fn, y0, "y0")] : vec(fn, y0, "y0").slice();309 var F = scalar ? function (t, v) { return [f(t, v[0])]; } : f, h = (t1 - t0) / n, ts = [t0], ys = [y];310 for (var i = 0; i < n; i++) {311 var t = t0 + i * h, k1 = F(t, y);312 if (order === 1) y = axpy(y, h, k1);313 else {314 var k2 = F(t + h / 2, axpy(y, h / 2, k1)), k3 = F(t + h / 2, axpy(y, h / 2, k2)), k4 = F(t + h, axpy(y, h, k3)), ny = new Array(y.length);315 for (var j = 0; j < y.length; j++) ny[j] = y[j] + h / 6 * (k1[j] + 2 * k2[j] + 2 * k3[j] + k4[j]);316 y = ny;317 }318 for (var c = 0; c < y.length; c++) if (!isNum(y[c])) fail(fn, "solution became non-finite at step " + (i + 1) + " (reduce the step)");319 ts.push(i === n - 1 ? t1 : t0 + (i + 1) * h); ys.push(y);320 }321 return {322 t: ts, y: scalar ? ys.map(function (v) { return v[0]; }) : ys,323 meta: meta(fn, { t0: t0, t1: t1, n: n, dt: h }, order === 1 ? "y_{n+1}=y_n+h\\,f(t_n,y_n)" : "y_{n+1}=y_n+\\tfrac{h}{6}(k_1+2k_2+2k_3+k_4)")324 };325 }326 /* f(t, y) → dy/dt ; y0 nombre (alors y = nombres) ou vecteur (alors y = vecteurs) */327 function rk4(f, y0, t0, t1, n) { return odeSolve("rk4", 4, f, y0, t0, t1, n); }328 function euler(f, y0, t0, t1, n) { return odeSolve("euler", 1, f, y0, t0, t1, n); }329 function pair(fn, r, name) { vec(fn, r, name, 2); if (r.length !== 2) fail(fn, name + " must be [min, max]"); return r; }330 /* f(x, y) → [u, v] */331 function vectorField(f, xRange, yRange, nx, ny) {332 fnArg("vectorField", f, "f"); pair("vectorField", xRange, "xRange"); pair("vectorField", yRange, "yRange");333 var xs = linspace(xRange[0], xRange[1], int("vectorField", nx, "nx", 2)), ys = linspace(yRange[0], yRange[1], int("vectorField", ny, "ny", 2)), pts = [], mx = 0;334 for (var j = 0; j < ny; j++) for (var i = 0; i < nx; i++) {335 var w = f(xs[i], ys[j]), mag = Math.sqrt(w[0] * w[0] + w[1] * w[1]);336 if (!isNum(mag)) fail("vectorField", "field is not finite at (" + xs[i] + ", " + ys[j] + ")");337 pts.push({ x: xs[i], y: ys[j], u: w[0], v: w[1], mag: mag }); if (mag > mx) mx = mag;338 }339 return { xs: xs, ys: ys, points: pts, maxMag: mx, meta: meta("vectorField", { xRange: xRange, yRange: yRange, nx: nx, ny: ny }, "\\mathbf{F}(x,y)=(u,v)") };340 }341 /* ligne de courant : intégration RK4 de dx/dt = F(x) avec le pas `step` (négatif pour remonter le champ) */342 function streamline(f, start, step, n) {343 fnArg("streamline", f, "f"); pair("streamline", start, "start"); num("streamline", step, "step"); int("streamline", n, "n", 1);344 var p = start.slice(), pts = [p], g = function (q) { return f(q[0], q[1]); };345 for (var i = 0; i < n; i++) {346 var k1 = g(p), k2 = g(axpy(p, step / 2, k1)), k3 = g(axpy(p, step / 2, k2)), k4 = g(axpy(p, step, k3));347 var q = [p[0] + step / 6 * (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0]), p[1] + step / 6 * (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1])];348 if (!isNum(q[0]) || !isNum(q[1])) break;349 pts.push(q); p = q;350 }351 return { points: pts, meta: meta("streamline", { start: start, step: step, n: n }, "\\dot{\\mathbf{x}}=\\mathbf{F}(\\mathbf{x})") };352 }353 /* grad(x) → vecteur gradient ; path contient x0 puis chaque itéré (steps + 1 points) */354 function gradientDescent(grad, x0, lr, steps) {355 fnArg("gradientDescent", grad, "grad"); vec("gradientDescent", x0, "x0"); pos("gradientDescent", lr, "lr"); int("gradientDescent", steps, "steps");356 var x = x0.slice(), path = [x];357 for (var i = 0; i < steps; i++) {358 x = axpy(x, -lr, grad(x));359 for (var j = 0; j < x.length; j++) if (!isNum(x[j])) fail("gradientDescent", "diverged at step " + (i + 1) + " (learning rate too large)");360 path.push(x);361 }362 return { path: path, meta: meta("gradientDescent", { x0: x0, lr: lr, steps: steps }, "x_{k+1}=x_k-\\eta\\,\\nabla f(x_k)") };363 }364 /* z[j][i] = f(xs[i], ys[j]) */365 function surface(f, xRange, yRange, nx, ny) {366 fnArg("surface", f, "f"); pair("surface", xRange, "xRange"); pair("surface", yRange, "yRange");367 var xs = linspace(xRange[0], xRange[1], int("surface", nx, "nx", 2)), ys = linspace(yRange[0], yRange[1], int("surface", ny, "ny", 2)), z = [], lo = Infinity, hi = -Infinity;368 for (var j = 0; j < ny; j++) {369 z.push([]);370 for (var i = 0; i < nx; i++) {371 var v = f(xs[i], ys[j]);372 if (!isNum(v)) fail("surface", "f is not finite at (" + xs[i] + ", " + ys[j] + ")");373 z[j].push(v); if (v < lo) lo = v; if (v > hi) hi = v;374 }375 }376 return { xs: xs, ys: ys, z: z, zMin: lo, zMax: hi, meta: meta("surface", { xRange: xRange, yRange: yRange, nx: nx, ny: ny }, "z=f(x,y)") };377 }378 function p3(fn, p) { vec(fn, p, "point", 3); if (p.length !== 3) fail(fn, "point must be [x, y, z]"); return p; }379 /* rotation d'angle `angle` (sens direct) autour de l'axe "x" | "y" | "z" */380 function rotate3d(point, axis, angle) {381 p3("rotate3d", point); num("rotate3d", angle, "angle");382 var c = Math.cos(angle), s = Math.sin(angle), x = point[0], y = point[1], z = point[2];383 if (axis === "x") return [x, y * c - z * s, y * s + z * c];384 if (axis === "y") return [x * c + z * s, y, -x * s + z * c];385 if (axis === "z") return [x * c - y * s, x * s + y * c, z];386 return fail("rotate3d", "axis must be \"x\", \"y\" or \"z\"");387 }388 /* Perspective simple, monde z vers le haut. camera = { yaw=0, pitch=0, distance=10, scale=1, cx=0, cy=0 }.389 yaw = rotation de la scène autour de z ; pitch > 0 = caméra qui regarde d'en haut ; à yaw = pitch = 0 la caméra regarde390 le long de +y (x vers la droite, z vers le haut de l'écran). Écran : y vers le BAS (convention SVG/canvas).391 factor = distance / (distance + depth) ; un point à depth ≤ −distance est derrière la caméra (visible = false). */392 function project3d(point, camera) {393 p3("project3d", point); camera = camera || {};394 var yaw = def(camera.yaw, 0), pitch = def(camera.pitch, 0), dist = pos("project3d", def(camera.distance, 10), "camera.distance"), sc = def(camera.scale, 1);395 var x1 = point[0] * Math.cos(yaw) - point[1] * Math.sin(yaw), y1 = point[0] * Math.sin(yaw) + point[1] * Math.cos(yaw), z1 = point[2];396 var up = z1 * Math.cos(pitch) - y1 * Math.sin(pitch), depth = y1 * Math.cos(pitch) + z1 * Math.sin(pitch), visible = dist + depth > 1e-9, f = visible ? dist / (dist + depth) : 0;397 return { x: def(camera.cx, 0) + sc * f * x1, y: def(camera.cy, 0) - sc * f * up, depth: depth, factor: f, visible: visible };398 }399400 /* ── apprentissage automatique (petit, exact, pour expliquer) ── */401 function softmax(v, temperature) {402 vec("softmax", v, "vec"); var T = pos("softmax", def(temperature, 1), "temperature");403 var m = Math.max.apply(null, v), e = v.map(function (x) { return Math.exp((x - m) / T); }), s = sum(e);404 return e.map(function (x) { return x / s; });405 }406 /* attention à produit scalaire normalisé : Q (n×d), K (m×d), V (m×dv) → weights (n×m, lignes de somme 1), output (n×dv) */407 function attention(Q, K, V) {408 mat("attention", Q, "Q"); mat("attention", K, "K"); mat("attention", V, "V");409 if (Q[0].length !== K[0].length) fail("attention", "Q and K must have the same number of columns");410 if (K.length !== V.length) fail("attention", "K and V must have the same number of rows");411 var s = Math.sqrt(K[0].length), scores = Q.map(function (q) { return K.map(function (k) { return dot(q, k) / s; }); });412 var weights = scores.map(function (r) { return softmax(r); });413 return { scores: scores, weights: weights, output: matmul(weights, V), meta: meta("scaledDotProductAttention", { dk: K[0].length }, "\\mathrm{Attention}(Q,K,V)=\\mathrm{softmax}\\!\\left(\\frac{QK^{\\top}}{\\sqrt{d_k}}\\right)V") };414 }415 /* encodage positionnel sinusoïdal (Vaswani et al., 2017) : composantes paires = sin, impaires = cos */416 function positionalEncoding(position, dim) {417 nonneg("positionalEncoding", position, "pos"); int("positionalEncoding", dim, "dim", 1);418 var out = new Array(dim);419 for (var i = 0; i < dim; i++) { var a = position / Math.pow(10000, 2 * Math.floor(i / 2) / dim); out[i] = i % 2 ? Math.cos(a) : Math.sin(a); }420 return out;421 }422 /* BPE JOUET et transparent : part des caractères (l'espace est un symbole comme un autre) et applique, dans l'ordre, la423 liste de fusions fournie [[a, b], …] (toutes les occurrences adjacentes, de gauche à droite). Ce n'est le vocabulaire424 d'AUCUN modèle réel : ne jamais le présenter comme la tokenisation de GPT, Claude, etc. */425 function tokenizeBpeDemo(text, merges) {426 if (typeof text !== "string") fail("tokenizeBpeDemo", "text must be a string");427 if (!Array.isArray(merges)) fail("tokenizeBpeDemo", "merges must be an array of [left, right] pairs");428 var tokens = Array.from(text), initial = tokens.slice(), steps = [];429 merges.forEach(function (m, idx) {430 if (!Array.isArray(m) || m.length !== 2 || typeof m[0] !== "string" || typeof m[1] !== "string" || !m[0] || !m[1]) fail("tokenizeBpeDemo", "merges[" + idx + "] must be a pair of non-empty strings");431 var out = [], count = 0;432 for (var i = 0; i < tokens.length; i++) {433 if (i < tokens.length - 1 && tokens[i] === m[0] && tokens[i + 1] === m[1]) { out.push(m[0] + m[1]); i++; count++; } else out.push(tokens[i]);434 }435 tokens = out;436 steps.push({ pair: [m[0], m[1]], merged: m[0] + m[1], count: count, tokens: tokens.slice() });437 });438 return { initial: initial, tokens: tokens, steps: steps, meta: meta("bpeDemo", { merges: merges.length }, "(a,b)\\mapsto ab", "Toy BPE applying a user-supplied merge list; not the vocabulary of any real model.") };439 }440 var ACT = {441 linear: function (z) { return z; }, tanh: function (z) { return Math.tanh(z); }, relu: function (z) { return z > 0 ? z : 0; },442 sigmoid: function (z) { return z >= 0 ? 1 / (1 + Math.exp(-z)) : Math.exp(z) / (1 + Math.exp(z)); }443 };444 /* layers = [{ W: [sorties][entrées], b: [sorties], act: "tanh" | "relu" | "sigmoid" | "linear" }] */445 function mlpForward(layers, x) {446 if (!Array.isArray(layers) || !layers.length) fail("mlpForward", "layers must be a non-empty array of { W, b, act }");447 var a = vec("mlpForward", x, "x"), acts = [a.slice()];448 layers.forEach(function (L, li) {449 var f = ACT[def(L.act, "linear")];450 if (!f) fail("mlpForward", "layers[" + li + "].act is unknown");451 if (!Array.isArray(L.W) || !L.W.length || L.W[0].length !== a.length || !Array.isArray(L.b) || L.b.length !== L.W.length) fail("mlpForward", "layers[" + li + "] has incompatible shapes");452 a = L.W.map(function (w, j) { return f(dot(w, a) + L.b[j]); });453 acts.push(a);454 });455 return { output: a, activations: acts };456 }457 /* Vrai petit MLP de classification binaire entraîné par rétropropagation (descente de gradient sur le lot complet).458 { layers: tailles, p. ex. [2, 4, 1] (sortie = 1 neurone sigmoïde), data: { X: [[…]], y: [0|1] }, lr, epochs, seed = 1,459 activation = "tanh" | "relu" (couches cachées), snapshotEvery = max(1, epochs/20), grid = { xRange, yRange, n = 24 } }460 Initialisation de Glorot uniforme (seed). loss[e] = entropie croisée moyenne AVANT la mise à jour e ; loss[epochs] = finale.461 snapshots (entrées de dimension 2 seulement) : z[j][i] = P(classe 1) en (grid.xs[i], grid.ys[j]).462 Référence testée : XOR, layers [2, 4, 1], tanh, lr 0.5, epochs 2000, seed 1 → perte finale < 0.05. */463 function mlpTrain(o) {464 o = o || {};465 var sizes = vec("mlpTrain", o.layers, "layers", 2), X = mat("mlpTrain", o.data && o.data.X, "data.X"), y = vec("mlpTrain", o.data && o.data.y, "data.y");466 var lr = pos("mlpTrain", o.lr, "lr"), epochs = int("mlpTrain", o.epochs, "epochs", 1), seed = def(o.seed, 1), hid = def(o.activation, "tanh"), N = X.length, li, i, j, k;467 if (hid !== "tanh" && hid !== "relu") fail("mlpTrain", "activation must be \"tanh\" or \"relu\"");468 if (sizes[0] !== X[0].length) fail("mlpTrain", "layers[0] must equal the input dimension " + X[0].length);469 if (sizes[sizes.length - 1] !== 1) fail("mlpTrain", "the last layer must have 1 unit (binary classification)");470 if (y.length !== N) fail("mlpTrain", "data.X and data.y must have the same length");471 for (i = 0; i < N; i++) if (y[i] !== 0 && y[i] !== 1) fail("mlpTrain", "data.y must contain only 0 or 1");472 for (i = 0; i < sizes.length; i++) int("mlpTrain", sizes[i], "layers[" + i + "]", 1);473 var r = rng(seed), layers = [];474 for (li = 1; li < sizes.length; li++) {475 var lim = Math.sqrt(6 / (sizes[li - 1] + sizes[li])), W = [], b = [];476 for (j = 0; j < sizes[li]; j++) { W.push([]); b.push(0); for (k = 0; k < sizes[li - 1]; k++) W[j].push((2 * r.next() - 1) * lim); }477 layers.push({ W: W, b: b, act: li === sizes.length - 1 ? "sigmoid" : hid });478 }479 var grid = null;480 if (sizes[0] === 2) {481 var g = o.grid || {}, c0 = X.map(function (p) { return p[0]; }), c1 = X.map(function (p) { return p[1]; });482 var xr = g.xRange || [Math.min.apply(null, c0) - 0.5, Math.max.apply(null, c0) + 0.5], yr = g.yRange || [Math.min.apply(null, c1) - 0.5, Math.max.apply(null, c1) + 0.5];483 grid = { xs: linspace(xr[0], xr[1], int("mlpTrain", def(g.n, 24), "grid.n", 2)), ys: linspace(yr[0], yr[1], def(g.n, 24)) };484 }485 var every = int("mlpTrain", def(o.snapshotEvery, Math.max(1, Math.floor(epochs / 20))), "snapshotEvery", 1), loss = [], accuracy = [], snapshots = [];486 function evaluate() {487 var L = 0, ok = 0;488 for (var n = 0; n < N; n++) {489 var p = clamp(mlpForward(layers, X[n]).output[0], 1e-12, 1 - 1e-12);490 L -= y[n] * Math.log(p) + (1 - y[n]) * Math.log(1 - p);491 if ((p >= 0.5 ? 1 : 0) === y[n]) ok++;492 }493 return [L / N, ok / N];494 }495 function snapshot(epoch, L) {496 if (!grid) return;497 snapshots.push({ epoch: epoch, loss: L, z: grid.ys.map(function (gy) { return grid.xs.map(function (gx) { return mlpForward(layers, [gx, gy]).output[0]; }); }) });498 }499 for (var e = 0; e <= epochs; e++) {500 var ev = evaluate();501 loss.push(ev[0]); accuracy.push(ev[1]);502 if (e % every === 0 || e === epochs) snapshot(e, ev[0]);503 if (e === epochs) break;504 var gW = layers.map(function (L) { return L.W.map(function (w) { return w.map(function () { return 0; }); }); }), gB = layers.map(function (L) { return L.b.map(function () { return 0; }); });505 for (var n = 0; n < N; n++) {506 var acts = mlpForward(layers, X[n]).activations, delta = [(acts[acts.length - 1][0] - y[n]) / N]; // ∂L/∂z de la sortie (sigmoïde + entropie croisée)507 for (li = layers.length - 1; li >= 0; li--) {508 var aIn = acts[li], prev = new Array(aIn.length);509 for (k = 0; k < aIn.length; k++) prev[k] = 0;510 for (j = 0; j < delta.length; j++) {511 gB[li][j] += delta[j];512 for (k = 0; k < aIn.length; k++) { gW[li][j][k] += delta[j] * aIn[k]; prev[k] += layers[li].W[j][k] * delta[j]; }513 }514 if (li > 0) for (k = 0; k < aIn.length; k++) prev[k] *= hid === "tanh" ? 1 - aIn[k] * aIn[k] : aIn[k] > 0 ? 1 : 0;515 delta = prev;516 }517 }518 for (li = 0; li < layers.length; li++) for (j = 0; j < layers[li].W.length; j++) {519 layers[li].b[j] -= lr * gB[li][j];520 for (k = 0; k < layers[li].W[j].length; k++) layers[li].W[j][k] -= lr * gW[li][j][k];521 }522 }523 return {524 layers: layers, loss: loss, accuracy: accuracy, snapshots: snapshots, grid: grid,525 meta: meta("mlpBackprop", { layers: sizes.slice(), lr: lr, epochs: epochs, seed: seed, activation: hid, samples: N }, "L=-\\tfrac{1}{N}\\sum_i\\left[y_i\\ln\\hat y_i+(1-y_i)\\ln(1-\\hat y_i)\\right],\\quad \\theta\\leftarrow\\theta-\\eta\\,\\nabla_\\theta L", "Genuine full-batch gradient descent on a tiny network; every loss value and snapshot is computed.")526 };527 }528 var datasets = {529 xor: function () { return { X: [[0, 0], [0, 1], [1, 0], [1, 1]], y: [0, 1, 1, 0], meta: meta("xor", {}, "y=x_1\\oplus x_2") }; },530 /* deux demi-lunes entrelacées (même géométrie que scikit-learn make_moons) + bruit gaussien d'écart-type `noise` */531 twoMoons: function (n, noise, seed) {532 int("datasets.twoMoons", n, "n", 2); noise = nonneg("datasets.twoMoons", def(noise, 0.1), "noise");533 var r = rng(def(seed, 1)), X = [], y = [], n0 = Math.ceil(n / 2), n1 = n - n0, i, t;534 for (i = 0; i < n0; i++) { t = n0 > 1 ? PI * i / (n0 - 1) : 0; X.push([Math.cos(t) + noise * r.normal(), Math.sin(t) + noise * r.normal()]); y.push(0); }535 for (i = 0; i < n1; i++) { t = n1 > 1 ? PI * i / (n1 - 1) : 0; X.push([1 - Math.cos(t) + noise * r.normal(), 0.5 - Math.sin(t) + noise * r.normal()]); y.push(1); }536 return { X: X, y: y, meta: meta("twoMoons", { n: n, noise: noise, seed: def(seed, 1) }, "(\\cos t,\\sin t)\\ \\text{et}\\ (1-\\cos t,\\ \\tfrac12-\\sin t),\\ t\\in[0,\\pi]", "Synthetic dataset.") };537 }538 };539 function cosineSimilarity(a, b) {540 vec("cosineSimilarity", a, "a"); vec("cosineSimilarity", b, "b");541 var na = Math.sqrt(dot(a, a)), nb = Math.sqrt(dot(b, b));542 if (na === 0 || nb === 0) fail("cosineSimilarity", "zero vector has no direction");543 return dot(a, b) / (na * nb);544 }545 /* ACP sur 2 axes : matrice de covariance (n−1) puis itération de puissance avec déflation.546 Signe fixé : la plus grande composante (en valeur absolue) de chaque axe est positive. */547 function pca2(points) {548 mat("pca2", points, "points");549 var n = points.length, d = points[0].length, i, j, k;550 if (n < 2 || d < 2) fail("pca2", "need at least 2 points of dimension >= 2");551 var mu = []; for (j = 0; j < d; j++) { mu.push(0); for (i = 0; i < n; i++) mu[j] += points[i][j] / n; }552 var Xc = points.map(function (p) { return p.map(function (v, c) { return v - mu[c]; }); }), C = [], total = 0;553 for (j = 0; j < d; j++) { C.push([]); for (k = 0; k < d; k++) { var s = 0; for (i = 0; i < n; i++) s += Xc[i][j] * Xc[i][k]; C[j].push(s / (n - 1)); } total += C[j][j]; }554 if (!(total > 0)) fail("pca2", "points have zero variance");555 var comps = [], vals = [];556 for (var c = 0; c < 2; c++) {557 var v = []; for (j = 0; j < d; j++) v.push(1 + 0.37 * j + 0.11 * c * (j % 2 ? 1 : -1)); // départ déterministe, non aligné sur un axe558 var lambda = 0;559 for (var it = 0; it < 2000; it++) {560 for (k = 0; k < comps.length; k++) v = axpy(v, -dot(v, comps[k]), comps[k]); // reste orthogonal aux axes trouvés561 var w = matvec(C, v), nw = Math.sqrt(dot(w, w));562 if (nw < 1e-14 * total) { lambda = 0; var nv = Math.sqrt(dot(v, v)); v = v.map(function (x) { return x / nv; }); break; }563 w = w.map(function (x) { return x / nw; });564 var diff = 0; for (j = 0; j < d; j++) diff += Math.abs(w[j] - v[j]);565 v = w; lambda = nw;566 if (diff < 1e-13) break;567 }568 var big = 0; for (j = 1; j < d; j++) if (Math.abs(v[j]) > Math.abs(v[big])) big = j;569 if (v[big] < 0) v = v.map(function (x) { return -x; });570 comps.push(v); vals.push(lambda);571 C = C.map(function (row, a) { return row.map(function (x, b) { return x - lambda * v[a] * v[b]; }); });572 }573 return {574 components: comps, explained: vals, explainedRatio: vals.map(function (l) { return l / total; }), mean: mu,575 projected: Xc.map(function (p) { return [dot(p, comps[0]), dot(p, comps[1])]; }),576 meta: meta("pca", { n: n, dim: d }, "\\Sigma v_k=\\lambda_k v_k,\\quad z_i=V^{\\top}(x_i-\\bar x)")577 };578 }579 /* k-moyennes de Lloyd, initialisation k-means++ ; opts = { seed = 1, maxIter = 100 } */580 function kmeans(points, k, opts) {581 mat("kmeans", points, "points"); int("kmeans", k, "k", 1); opts = opts || {};582 if (k > points.length) fail("kmeans", "k must be <= number of points");583 var r = rng(def(opts.seed, 1)), maxIter = int("kmeans", def(opts.maxIter, 100), "maxIter", 1), n = points.length, i, c;584 function d2(a, b) { var s = 0; for (var j = 0; j < a.length; j++) s += (a[j] - b[j]) * (a[j] - b[j]); return s; }585 var cents = [points[r.int(n)].slice()];586 while (cents.length < k) {587 var ds = points.map(function (p) { var m = Infinity; for (var q = 0; q < cents.length; q++) m = Math.min(m, d2(p, cents[q])); return m; }), tot = sum(ds), u = r.next() * tot, pick = n - 1;588 for (i = 0; i < n; i++) { u -= ds[i]; if (u < 0) { pick = i; break; } }589 cents.push(points[pick].slice());590 }591 var labels = new Array(n), iter = 0, changed = true;592 while (changed && iter < maxIter) {593 changed = false; iter++;594 for (i = 0; i < n; i++) { var best = 0; for (c = 1; c < k; c++) if (d2(points[i], cents[c]) < d2(points[i], cents[best])) best = c; if (labels[i] !== best) { labels[i] = best; changed = true; } }595 for (c = 0; c < k; c++) {596 var acc = points[0].map(function () { return 0; }), cnt = 0;597 for (i = 0; i < n; i++) if (labels[i] === c) { cnt++; for (var j = 0; j < acc.length; j++) acc[j] += points[i][j]; }598 if (cnt) cents[c] = acc.map(function (x) { return x / cnt; }); // amas vide : le centre précédent est conservé599 }600 }601 var inertia = 0; for (i = 0; i < n; i++) inertia += d2(points[i], cents[labels[i]]);602 return { centroids: cents, labels: labels, inertia: inertia, iterations: iter, meta: meta("kmeans", { k: k, seed: def(opts.seed, 1), n: n }, "\\min_{C}\\sum_i\\min_k\\lVert x_i-c_k\\rVert^2") };603 }604605 /* ── finance ── */606 /* valeur future ; m = nombre de capitalisations par an (Infinity = continue) */607 function compound(pv, rate, years, m) {608 num("compound", pv, "pv"); num("compound", rate, "rate"); num("compound", years, "years"); m = def(m, 1);609 if (m === Infinity) return pv * Math.exp(rate * years);610 pos("compound", m, "m"); if (1 + rate / m <= 0) fail("compound", "need 1 + rate/m > 0");611 return pv * Math.pow(1 + rate / m, m * years);612 }613 function presentValue(fv, rate, years, m) { num("presentValue", fv, "fv"); return fv / compound(1, rate, years, m); }614 /* rente ordinaire (paiements en fin de période) : n paiements au taux périodique `rate` */615 function annuityPv(payment, rate, n) {616 num("annuityPv", payment, "payment"); num("annuityPv", rate, "rate"); nonneg("annuityPv", n, "n");617 if (rate <= -1) fail("annuityPv", "rate must be > -1");618 return rate === 0 ? payment * n : payment * (1 - Math.pow(1 + rate, -n)) / rate;619 }620 /* cashflows[t] reçu à la fin de la période t (cashflows[0] = aujourd'hui) */621 function npv(rate, cashflows) {622 num("npv", rate, "rate"); vec("npv", cashflows, "cashflows"); if (rate <= -1) fail("npv", "rate must be > -1");623 var s = 0; for (var t = 0; t < cashflows.length; t++) s += cashflows[t] / Math.pow(1 + rate, t);624 return s;625 }626 /* TRI par bissection sur [lo, hi] (défaut [−0.99, 10]) ; erreur si la VAN ne change pas de signe sur l'intervalle.627 Avec plusieurs changements de signe des flux, il peut exister plusieurs TRI : resserrer l'intervalle. */628 function irr(cashflows, opts) {629 vec("irr", cashflows, "cashflows", 2); opts = opts || {};630 var lo = def(opts.lo, -0.99), hi = def(opts.hi, 10), flo = npv(lo, cashflows), fhi = npv(hi, cashflows);631 if (flo === 0) return lo; if (fhi === 0) return hi;632 if (flo * fhi > 0) fail("irr", "NPV does not change sign on [" + lo + ", " + hi + "]: no IRR bracketed");633 for (var i = 0; i < 200 && hi - lo > 1e-14; i++) { var mid = (lo + hi) / 2, fm = npv(mid, cashflows); if (fm === 0) return mid; if (fm * flo > 0) { lo = mid; flo = fm; } else hi = mid; }634 return (lo + hi) / 2;635 }636 var BS_FORMULA = "C=Se^{-qT}N(d_1)-Ke^{-rT}N(d_2),\\ P=Ke^{-rT}N(-d_2)-Se^{-qT}N(-d_1),\\ d_{1,2}=\\frac{\\ln(S/K)+(r-q\\pm\\sigma^2/2)T}{\\sigma\\sqrt{T}}";637 function bsArgs(fn, o) {638 o = o || {};639 var a = { S: pos(fn, o.S, "S"), K: pos(fn, o.K, "K"), r: num(fn, def(o.r, 0), "r"), T: pos(fn, o.T, "T"), q: num(fn, def(o.q, 0), "q"), type: def(o.type, "call") };640 if (a.type !== "call" && a.type !== "put") fail(fn, "type must be \"call\" or \"put\"");641 return a;642 }643 function bsPrice(a, sigma) {644 var sq = sigma * Math.sqrt(a.T), d1 = (Math.log(a.S / a.K) + (a.r - a.q + sigma * sigma / 2) * a.T) / sq, d2 = d1 - sq, df = Math.exp(-a.r * a.T), dq = Math.exp(-a.q * a.T);645 return a.type === "call" ? a.S * dq * normalCdf(d1) - a.K * df * normalCdf(d2) : a.K * df * normalCdf(-d2) - a.S * dq * normalCdf(-d1);646 }647 /* Black–Scholes–Merton (option européenne, dividende continu q). Grecques : vega et rho par unité (1.00 = 100 points)648 de volatilité / de taux ; theta par AN (diviser par 365 pour un jour). */649 function blackScholes(o) {650 var a = bsArgs("blackScholes", o), sigma = pos("blackScholes", o.sigma, "sigma"), sqT = Math.sqrt(a.T);651 var d1 = (Math.log(a.S / a.K) + (a.r - a.q + sigma * sigma / 2) * a.T) / (sigma * sqT), d2 = d1 - sigma * sqT, df = Math.exp(-a.r * a.T), dq = Math.exp(-a.q * a.T), call = a.type === "call", pdf = normalPdf(d1);652 var decay = -a.S * dq * pdf * sigma / (2 * sqT);653 return {654 price: bsPrice(a, sigma),655 delta: call ? dq * normalCdf(d1) : dq * (normalCdf(d1) - 1),656 gamma: dq * pdf / (a.S * sigma * sqT),657 vega: a.S * dq * pdf * sqT,658 theta: call ? decay - a.r * a.K * df * normalCdf(d2) + a.q * a.S * dq * normalCdf(d1) : decay + a.r * a.K * df * normalCdf(-d2) - a.q * a.S * dq * normalCdf(-d1),659 rho: call ? a.K * a.T * df * normalCdf(d2) : -a.K * a.T * df * normalCdf(-d2),660 d1: d1, d2: d2,661 meta: meta("blackScholes", { S: a.S, K: a.K, r: a.r, sigma: sigma, T: a.T, q: a.q, type: a.type }, BS_FORMULA)662 };663 }664 /* volatilité implicite par bissection sur [1e-6, 10] ; erreur si le prix viole les bornes d'absence d'arbitrage */665 function impliedVol(price, o) {666 var a = bsArgs("impliedVol", o); num("impliedVol", price, "price");667 var df = Math.exp(-a.r * a.T), dq = Math.exp(-a.q * a.T), call = a.type === "call";668 var lower = Math.max(0, call ? a.S * dq - a.K * df : a.K * df - a.S * dq), upper = call ? a.S * dq : a.K * df;669 if (!(price > lower && price < upper)) fail("impliedVol", "price " + price + " is outside the no-arbitrage bounds (" + lower + ", " + upper + ")");670 var lo = 1e-6, hi = 10;671 if (bsPrice(a, lo) > price || bsPrice(a, hi) < price) fail("impliedVol", "no volatility in [1e-6, 10] reproduces this price");672 for (var i = 0; i < 200 && hi - lo > 1e-13; i++) { var mid = (lo + hi) / 2; if (bsPrice(a, mid) < price) lo = mid; else hi = mid; }673 return (lo + hi) / 2;674 }675 /* Surface de volatilité PARAMÉTRIQUE et illustrative (jamais des cotations). k = ln(K/F), F = S·e^{rT}.676 "flat" : params { sigma } σ = sigma677 "skew" : params { sigma, skew = -0.1, smile = 0.1, term = 0 } σ = sigma + skew·k/√T + smile·k² + term·√T (borné ≥ 0.01)678 "svi" : params { a, b, rho, m, sigma } variance totale w(k,T) = T·[a + b(ρ(k−m) + √((k−m)²+σ²))], σ_imp = √(w/T)679 (SVI « raw » de Gatheral, mêmes paramètres annualisés pour toutes les échéances). iv[i][j] : maturité i, strike j. */680 function volSurface(o) {681 o = o || {};682 var S = pos("volSurface", o.S, "S"), r = num("volSurface", def(o.r, 0), "r"), Ks = vec("volSurface", o.strikes, "strikes"), Ts = vec("volSurface", o.maturities, "maturities"), model = def(o.model, "flat"), p = o.params || {}, f, formula;683 Ks.forEach(function (K) { pos("volSurface", K, "strike"); }); Ts.forEach(function (T) { pos("volSurface", T, "maturity"); });684 if (model === "flat") { var s0 = pos("volSurface", p.sigma, "params.sigma"); f = function () { return s0; }; formula = "\\sigma(K,T)=\\sigma_0"; }685 else if (model === "skew") {686 var s1 = pos("volSurface", p.sigma, "params.sigma"), sk = num("volSurface", def(p.skew, -0.1), "params.skew"), sm = num("volSurface", def(p.smile, 0.1), "params.smile"), tm = num("volSurface", def(p.term, 0), "params.term");687 f = function (k, T) { return Math.max(0.01, s1 + sk * k / Math.sqrt(T) + sm * k * k + tm * Math.sqrt(T)); };688 formula = "\\sigma(k,T)=\\sigma_0+s\\,\\frac{k}{\\sqrt{T}}+c\\,k^2+\\tau\\sqrt{T},\\quad k=\\ln(K/F)";689 } else if (model === "svi") {690 var a = num("volSurface", p.a, "params.a"), b = nonneg("volSurface", p.b, "params.b"), rho = num("volSurface", p.rho, "params.rho"), m = num("volSurface", p.m, "params.m"), sg = pos("volSurface", p.sigma, "params.sigma");691 if (Math.abs(rho) >= 1) fail("volSurface", "SVI needs |rho| < 1");692 if (a + b * sg * Math.sqrt(1 - rho * rho) <= 0) fail("volSurface", "SVI needs a + b*sigma*sqrt(1-rho^2) > 0 (positive variance)");693 f = function (k) { return Math.sqrt(a + b * (rho * (k - m) + Math.sqrt((k - m) * (k - m) + sg * sg))); };694 formula = "w(k,T)=T\\left[a+b\\left(\\rho(k-m)+\\sqrt{(k-m)^2+\\sigma^2}\\right)\\right],\\ \\sigma_{imp}=\\sqrt{w/T},\\ k=\\ln(K/F)";695 } else fail("volSurface", "model must be \"flat\", \"skew\" or \"svi\"");696 var lo = Infinity, hi = -Infinity, iv = Ts.map(function (T) { return Ks.map(function (K) { var v = f(Math.log(K / (S * Math.exp(r * T))), T); if (v < lo) lo = v; if (v > hi) hi = v; return v; }); });697 return { strikes: Ks.slice(), maturities: Ts.slice(), iv: iv, ivMin: lo, ivMax: hi, meta: meta("volSurface:" + model, { S: S, r: r, params: p }, formula, "Parametric illustrative surface computed from a formula; NOT observed market quotes.") };698 }699 /* mouvement brownien géométrique, schéma exact ; paths[i][j] = prix de la trajectoire i à t[j] */700 function gbmPaths(o) {701 o = o || {};702 var S0 = pos("gbmPaths", o.S0, "S0"), mu = num("gbmPaths", o.mu, "mu"), sigma = nonneg("gbmPaths", o.sigma, "sigma"), T = pos("gbmPaths", o.T, "T"), steps = int("gbmPaths", o.steps, "steps", 1), n = int("gbmPaths", def(o.n, 1), "n", 1), seed = def(o.seed, 1);703 var r = rng(seed), dt = T / steps, drift = (mu - sigma * sigma / 2) * dt, vol = sigma * Math.sqrt(dt), paths = [];704 for (var i = 0; i < n; i++) { var p = [S0], s = S0; for (var j = 0; j < steps; j++) { s *= Math.exp(drift + vol * r.normal()); p.push(s); } paths.push(p); }705 return { t: linspace(0, T, steps + 1), paths: paths, meta: meta("gbm", { S0: S0, mu: mu, sigma: sigma, T: T, steps: steps, n: n, seed: seed }, "S_{t+\\Delta t}=S_t\\exp\\!\\left[(\\mu-\\tfrac{\\sigma^2}{2})\\Delta t+\\sigma\\sqrt{\\Delta t}\\,Z\\right],\\ Z\\sim N(0,1)", "Simulated paths, not market prices.") };706 }707 /* VaR historique : perte (nombre positif) dépassée avec une probabilité 1 − level ; quantile de type 7 */708 function valueAtRisk(returns, level) {709 level = def(level, 0.95); if (!(level > 0 && level < 1)) fail("valueAtRisk", "level must be in (0, 1)");710 return -quantile(vec("valueAtRisk", returns, "returns", 2), 1 - level);711 }712 function var95(returns) { return valueAtRisk(returns, 0.95); }713 /* perte moyenne (positive) des rendements ≤ au quantile 1 − level (défaut 0.95) */714 function expectedShortfall(returns, level) {715 level = def(level, 0.95); var q = -valueAtRisk(returns, level), tail = returns.filter(function (x) { return x <= q; });716 return -mean(tail);717 }718 function portfolioArgs(fn, mu, cov) {719 vec(fn, mu, "mu", 2); square(fn, cov, "cov");720 if (cov.length !== mu.length) fail(fn, "cov must be " + mu.length + "x" + mu.length);721 cholesky(cov); // lève une erreur si cov n'est pas symétrique définie positive722 }723 function pfStats(fn, weights, mu, cov) {724 vec(fn, weights, "weights"); vec(fn, mu, "mu"); square(fn, cov, "cov");725 if (weights.length !== mu.length || cov.length !== mu.length) fail(fn, "weights, mu and cov must have matching sizes");726 var v = dot(weights, matvec(cov, weights));727 return { ret: dot(weights, mu), variance: v, risk: Math.sqrt(Math.max(0, v)) };728 }729 function portfolioStats(weights, mu, cov) { return pfStats("portfolioStats", weights, mu, cov); }730 function sharpe(weights, mu, cov, rf) { var s = pfStats("sharpe", weights, mu, cov); if (!(s.risk > 0)) fail("sharpe", "portfolio has zero risk"); return (s.ret - num("sharpe", def(rf, 0), "rf")) / s.risk; }731 /* portefeuille de variance minimale w = Σ⁻¹1 / (1ᵀΣ⁻¹1) (ventes à découvert permises) ; mu facultatif pour `ret` */732 function minVariancePortfolio(cov, mu) {733 square("minVariancePortfolio", cov, "cov"); cholesky(cov);734 var ones = cov.map(function () { return 1; }), x = solve(cov, ones), A = sum(x), w = x.map(function (v) { return v / A; });735 var out = { weights: w, variance: 1 / A, risk: Math.sqrt(1 / A), meta: meta("minVariance", { n: cov.length }, "w=\\frac{\\Sigma^{-1}\\mathbf{1}}{\\mathbf{1}^{\\top}\\Sigma^{-1}\\mathbf{1}}", "Short sales allowed (weights may be negative).") };736 if (mu) out.ret = dot(w, vec("minVariancePortfolio", mu, "mu"));737 return out;738 }739 /* portefeuille tangent w ∝ Σ⁻¹(μ − rf·1), normalisé à somme 1 ; exige rf < rendement du portefeuille de variance minimale */740 function tangencyPortfolio(mu, cov, rf) {741 portfolioArgs("tangencyPortfolio", mu, cov); rf = num("tangencyPortfolio", def(rf, 0), "rf");742 var x = solve(cov, mu.map(function (m) { return m - rf; })), s = sum(x);743 if (!(s > 1e-12)) fail("tangencyPortfolio", "rf must be below the minimum-variance portfolio return (no tangency portfolio on the efficient branch)");744 var w = x.map(function (v) { return v / s; }), st = portfolioStats(w, mu, cov);745 return { weights: w, ret: st.ret, risk: st.risk, sharpe: (st.ret - rf) / st.risk, meta: meta("tangency", { rf: rf, n: mu.length }, "w=\\frac{\\Sigma^{-1}(\\mu-r_f\\mathbf{1})}{\\mathbf{1}^{\\top}\\Sigma^{-1}(\\mu-r_f\\mathbf{1})}", "Short sales allowed (weights may be negative).") };746 }747 /* Frontière de Markowitz en forme fermée (multiplicateurs de Lagrange, séparation en deux fonds), SANS contrainte de748 vente à découvert : les poids peuvent être négatifs. A = 1ᵀΣ⁻¹1, B = 1ᵀΣ⁻¹μ, C = μᵀΣ⁻¹μ, D = AC − B².749 n points de rendement cible de retMin (défaut B/A, variance minimale) à retMax (défaut max(mu)). */750 function efficientFrontier(o) {751 o = o || {}; portfolioArgs("efficientFrontier", o.mu, o.cov);752 var mu = o.mu, cov = o.cov, n = int("efficientFrontier", def(o.n, 30), "n", 2), ones = mu.map(function () { return 1; }), s1 = solve(cov, ones), sm = solve(cov, mu);753 var A = sum(s1), B = sum(sm), C = dot(mu, sm), D = A * C - B * B;754 if (!(D > 1e-14 * A * C)) fail("efficientFrontier", "all expected returns are equal: the frontier is degenerate");755 var lo = num("efficientFrontier", def(o.retMin, B / A), "retMin"), hi = num("efficientFrontier", def(o.retMax, Math.max.apply(null, mu)), "retMax");756 var points = linspace(lo, hi, n).map(function (m) {757 var w = s1.map(function (v, i) { return ((C - B * m) * v + (A * m - B) * sm[i]) / D; }), variance = (A * m * m - 2 * B * m + C) / D;758 return { ret: m, risk: Math.sqrt(variance), variance: variance, weights: w };759 });760 return {761 points: points, minVariance: { ret: B / A, risk: Math.sqrt(1 / A), weights: s1.map(function (v) { return v / A; }) }, coefficients: { A: A, B: B, C: C, D: D },762 meta: meta("efficientFrontier", { n: n, assets: mu.length }, "\\sigma_p^2(m)=\\frac{Am^2-2Bm+C}{D},\\ w(m)=\\frac{(C-Bm)\\Sigma^{-1}\\mathbf{1}+(Am-B)\\Sigma^{-1}\\mu}{D}", "Closed-form frontier without short-sale constraint (weights may be negative); inputs are model assumptions.")763 };764 }765 /* Nelson–Siegel : y(τ) = b0 + b1·(1−e^{−x})/x + b2·((1−e^{−x})/x − e^{−x}), x = τ/λ (λ = constante de temps, même unité que τ) */766 function nelsonSiegel(tau, p) {767 nonneg("nelsonSiegel", tau, "tau"); p = p || {};768 var b0 = num("nelsonSiegel", p.b0, "b0"), b1 = num("nelsonSiegel", p.b1, "b1"), b2 = num("nelsonSiegel", p.b2, "b2"), x = tau / pos("nelsonSiegel", p.lambda, "lambda");769 if (x < 1e-8) return b0 + b1 * (1 - x / 2) + b2 * (x / 2); // développement limité près de τ = 0770 var e = Math.exp(-x), load = (1 - e) / x;771 return b0 + b1 * load + b2 * (load - e);772 }773 function yieldCurve(maturities, params) {774 vec("yieldCurve", maturities, "maturities");775 return { maturities: maturities.slice(), yields: maturities.map(function (t) { return nelsonSiegel(t, params); }), meta: meta("nelsonSiegel", params, "y(\\tau)=\\beta_0+\\beta_1\\frac{1-e^{-\\tau/\\lambda}}{\\tau/\\lambda}+\\beta_2\\left(\\frac{1-e^{-\\tau/\\lambda}}{\\tau/\\lambda}-e^{-\\tau/\\lambda}\\right)", "Parametric curve, not observed yields.") };776 }777 function px(x) { return Math.round(x * 1e8) / 1e8; }778 /* Carnet d'ordres à cours limité SYNTHÉTIQUE : `levels` niveaux de chaque côté, espacés de `tick`, meilleur achat à779 mid − tick/2 et meilleure vente à mid + tick/2 (écart = tick). Quantité entière du niveau i ≈ depth·(1 + 0.15·i)·U(0.5, 1.5).780 bids et asks sont triés du meilleur au moins bon. */781 function orderBook(o) {782 o = o || {};783 var mid = pos("orderBook", o.mid, "mid"), levels = int("orderBook", o.levels, "levels", 1), tick = pos("orderBook", o.tick, "tick"), depth = pos("orderBook", o.depth, "depth"), seed = def(o.seed, 1), r = rng(seed), bids = [], asks = [];784 if (mid - tick * (levels - 0.5) <= 0) fail("orderBook", "too many levels: bid prices would reach 0");785 for (var i = 0; i < levels; i++) {786 bids.push({ price: px(mid - tick * (i + 0.5)), qty: Math.max(1, Math.round(depth * (1 + 0.15 * i) * (0.5 + r.next()))) });787 asks.push({ price: px(mid + tick * (i + 0.5)), qty: Math.max(1, Math.round(depth * (1 + 0.15 * i) * (0.5 + r.next()))) });788 }789 return { mid: mid, tick: tick, spread: px(asks[0].price - bids[0].price), bids: bids, asks: asks, meta: meta("syntheticOrderBook", { mid: mid, levels: levels, tick: tick, depth: depth, seed: seed }, "p^{bid}_i=m-(i+\\tfrac12)\\delta,\\quad p^{ask}_i=m+(i+\\tfrac12)\\delta", "Synthetic order book generated from a seed; NOT a real market snapshot.") };790 }791 /* Ordre au marché : "buy" consomme les ventes (asks), "sell" les achats (bids), du meilleur prix au moins bon.792 Ne modifie pas `book` ; bookAfter est le carnet restant. slippage = écart défavorable du prix moyen au mid (≥ 0). */793 function matchMarketOrder(book, side, qty) {794 if (!book || !Array.isArray(book.bids) || !Array.isArray(book.asks) || !isNum(book.mid)) fail("matchMarketOrder", "book must come from SKN.orderBook");795 if (side !== "buy" && side !== "sell") fail("matchMarketOrder", "side must be \"buy\" or \"sell\"");796 pos("matchMarketOrder", qty, "qty");797 var src = side === "buy" ? book.asks : book.bids, left = qty, fills = [], rest = [], cost = 0;798 for (var i = 0; i < src.length; i++) {799 var take = Math.min(left, src[i].qty);800 if (take > 0) { fills.push({ price: src[i].price, qty: take }); cost += take * src[i].price; left -= take; }801 if (src[i].qty - take > 0) rest.push({ price: src[i].price, qty: src[i].qty - take });802 }803 var filled = qty - left, avg = filled > 0 ? cost / filled : null, slip = avg == null ? null : side === "buy" ? avg - book.mid : book.mid - avg, copy = function (l) { return l.map(function (x) { return { price: x.price, qty: x.qty }; }); };804 return {805 side: side, requested: qty, filled: filled, unfilled: left, fills: fills, avgPrice: avg, slippage: slip, slippageBps: slip == null ? null : slip / book.mid * 1e4,806 bookAfter: { mid: book.mid, tick: book.tick, bids: side === "sell" ? rest : copy(book.bids), asks: side === "buy" ? rest : copy(book.asks) }807 };808 }809 /* chandeliers : la barre i couvre path[i·barSize … (i+1)·barSize] (bornes incluses : open = close de la barre précédente) ;810 les points restants insuffisants pour une barre complète sont ignorés. Renvoie [{ open, high, low, close, start, end }]. */811 function ohlcFromPath(path, barSize) {812 vec("ohlcFromPath", path, "path", 2); int("ohlcFromPath", barSize, "barSize", 1);813 var bars = [];814 for (var s = 0; s + barSize < path.length; s += barSize) {815 var seg = path.slice(s, s + barSize + 1);816 bars.push({ open: seg[0], high: Math.max.apply(null, seg), low: Math.min.apply(null, seg), close: seg[barSize], start: s, end: s + barSize });817 }818 return bars;819 }820 /* écart-type glissant (n−1) × √annualization ; null tant que la fenêtre n'est pas pleine */821 function rollingVolatility(returns, window, annualization) {822 vec("rollingVolatility", returns, "returns"); int("rollingVolatility", window, "window", 2); var k = Math.sqrt(pos("rollingVolatility", def(annualization, 1), "annualization"));823 return returns.map(function (_, i) { return i < window - 1 ? null : std(returns.slice(i - window + 1, i + 1)) * k; });824 }825 /* GARCH(1,1) simulé : r_t = σ_t z_t, σ²_t = ω + α r²_{t−1} + β σ²_{t−1}, z ~ N(0,1).826 Stationnarité en covariance : α + β < 1 (sinon Error) ; variance inconditionnelle ω/(1−α−β), valeur initiale de σ². */827 function garch11(o) {828 o = o || {};829 var omega = pos("garch11", o.omega, "omega"), alpha = nonneg("garch11", o.alpha, "alpha"), beta = nonneg("garch11", o.beta, "beta"), n = int("garch11", o.n, "n", 1), seed = def(o.seed, 1);830 if (alpha + beta >= 1) fail("garch11", "not covariance-stationary: need alpha + beta < 1");831 var r = rng(seed), uv = omega / (1 - alpha - beta), s2 = uv, rets = [], sig2 = [];832 for (var i = 0; i < n; i++) { sig2.push(s2); var x = Math.sqrt(s2) * r.normal(); rets.push(x); s2 = omega + alpha * x * x + beta * s2; }833 return { returns: rets, sigma2: sig2, unconditionalVariance: uv, meta: meta("garch11", { omega: omega, alpha: alpha, beta: beta, n: n, seed: seed }, "r_t=\\sigma_t z_t,\\ \\sigma_t^2=\\omega+\\alpha r_{t-1}^2+\\beta\\sigma_{t-1}^2,\\ \\alpha+\\beta<1", "Simulated series, not market returns.") };834 }835836 /* ── physique ── */837 /* tir sans frottement (forme fermée échantillonnée tous les dt, dernier point = impact au sol y = 0) ; angle en radians */838 function projectile(o) {839 o = o || {};840 var v0 = pos("projectile", o.v0, "v0"), angle = num("projectile", o.angle, "angle"), g = pos("projectile", def(o.g, 9.81), "g"), dt = pos("projectile", def(o.dt, 0.01), "dt"), y0 = nonneg("projectile", def(o.y0, 0), "y0");841 var vx = v0 * Math.cos(angle), vy = v0 * Math.sin(angle), tf = (vy + Math.sqrt(vy * vy + 2 * g * y0)) / g;842 if (!(tf > 0)) fail("projectile", "the projectile never flies (angle must point upward when y0 = 0)");843 if (tf / dt > 1e6) fail("projectile", "dt is too small for this flight time");844 var t = [], x = [], y = [];845 for (var i = 0; i * dt < tf; i++) { t.push(i * dt); x.push(vx * i * dt); y.push(y0 + vy * i * dt - g * i * dt * i * dt / 2); }846 t.push(tf); x.push(vx * tf); y.push(0);847 return { t: t, x: x, y: y, flightTime: tf, range: vx * tf, maxHeight: y0 + (vy > 0 ? vy * vy / (2 * g) : 0), meta: meta("projectile", { v0: v0, angle: angle, g: g, dt: dt, y0: y0 }, "x=v_0\\cos\\theta\\,t,\\quad y=y_0+v_0\\sin\\theta\\,t-\\tfrac12 g t^2") };848 }849 /* pendule simple NON linéarisé, RK4 : θ'' = −(g/L) sin θ − damping·θ' */850 function pendulum(o) {851 o = o || {};852 var th0 = num("pendulum", o.theta0, "theta0"), w0 = num("pendulum", def(o.omega0, 0), "omega0"), L = pos("pendulum", o.L, "L"), g = pos("pendulum", def(o.g, 9.81), "g"), dt = pos("pendulum", o.dt, "dt"), n = int("pendulum", o.n, "n", 1), c = nonneg("pendulum", def(o.damping, 0), "damping");853 var s = odeSolve("pendulum", 4, function (t, y) { return [y[1], -g / L * Math.sin(y[0]) - c * y[1]]; }, [th0, w0], 0, n * dt, n);854 return { t: s.t, theta: s.y.map(function (v) { return v[0]; }), omega: s.y.map(function (v) { return v[1]; }), smallAnglePeriod: 2 * PI * Math.sqrt(L / g), meta: meta("pendulum", { theta0: th0, omega0: w0, L: L, g: g, dt: dt, n: n, damping: c }, "\\ddot\\theta=-\\frac{g}{L}\\sin\\theta-c\\,\\dot\\theta") };855 }856 /* masse–ressort amorti, RK4 : m x'' = −k x − c x' ; energy = ½ m v² + ½ k x² */857 function springMass(o) {858 o = o || {};859 var m = pos("springMass", o.m, "m"), k = pos("springMass", o.k, "k"), c = nonneg("springMass", def(o.c, 0), "c"), x0 = num("springMass", o.x0, "x0"), v0 = num("springMass", def(o.v0, 0), "v0"), dt = pos("springMass", o.dt, "dt"), n = int("springMass", o.n, "n", 1);860 var s = odeSolve("springMass", 4, function (t, y) { return [y[1], (-k * y[0] - c * y[1]) / m]; }, [x0, v0], 0, n * dt, n);861 return { t: s.t, x: s.y.map(function (v) { return v[0]; }), v: s.y.map(function (v) { return v[1]; }), energy: s.y.map(function (v) { return 0.5 * m * v[1] * v[1] + 0.5 * k * v[0] * v[0]; }), omega0: Math.sqrt(k / m), period: 2 * PI * Math.sqrt(m / k), meta: meta("springMass", { m: m, k: k, c: c, x0: x0, v0: v0, dt: dt, n: n }, "m\\ddot x=-kx-c\\dot x") };862 }863 /* Un pas de Verlet vitesse pour N corps en gravitation newtonienne 2D. bodies = [{ m, x, y, vx, vy }] ; renvoie un NOUVEAU864 tableau (entrée intacte). softening ε : distance au carré r² + ε² (évite la singularité des rencontres proches). */865 function nBodyStep(bodies, dt, G, softening) {866 if (!Array.isArray(bodies) || !bodies.length) fail("nBodyStep", "bodies must be a non-empty array of { m, x, y, vx, vy }");867 num("nBodyStep", dt, "dt"); G = pos("nBodyStep", def(G, 1), "G"); var eps = nonneg("nBodyStep", def(softening, 0), "softening");868 bodies.forEach(function (b, i) { pos("nBodyStep", b && b.m, "bodies[" + i + "].m"); ["x", "y", "vx", "vy"].forEach(function (k) { num("nBodyStep", b[k], "bodies[" + i + "]." + k); }); });869 function acc(bs) {870 return bs.map(function (a, i) {871 var ax = 0, ay = 0;872 for (var j = 0; j < bs.length; j++) if (j !== i) {873 var dx = bs[j].x - a.x, dy = bs[j].y - a.y, r2 = dx * dx + dy * dy + eps * eps;874 if (r2 === 0) fail("nBodyStep", "two bodies coincide (use softening > 0)");875 var f = G * bs[j].m / (r2 * Math.sqrt(r2)); ax += f * dx; ay += f * dy;876 }877 return [ax, ay];878 });879 }880 var a0 = acc(bodies), next = bodies.map(function (b, i) { return { m: b.m, x: b.x + b.vx * dt + 0.5 * a0[i][0] * dt * dt, y: b.y + b.vy * dt + 0.5 * a0[i][1] * dt * dt, vx: b.vx, vy: b.vy }; }), a1 = acc(next);881 next.forEach(function (b, i) { b.vx += 0.5 * (a0[i][0] + a1[i][0]) * dt; b.vy += 0.5 * (a0[i][1] + a1[i][1]) * dt; });882 return next;883 }884 function pdeSetup(fn, o) {885 var n = int(fn, o.n, "n", 3), dx = pos(fn, o.dx, "dx"), dt = pos(fn, o.dt, "dt"), steps = int(fn, o.steps, "steps", 1), every = int(fn, def(o.every, 1), "every", 1), x = [], u, i;886 for (i = 0; i < n; i++) x.push(i * dx);887 if (typeof o.initial === "function") u = x.map(function (v) { return o.initial(v); });888 else { u = vec(fn, o.initial, "initial").slice(); if (u.length !== n) fail(fn, "initial must have n = " + n + " values"); }889 vec(fn, u, "initial");890 return { n: n, dx: dx, dt: dt, steps: steps, every: every, x: x, u: u };891 }892 /* Équation des ondes u_tt = c² u_xx sur x_i = i·dx (i = 0…n−1), extrémités FIXES (valeurs initiales), vitesse initiale nulle.893 Schéma explicite centré ; stabilité CFL : c·dt/dx ≤ 1 (sinon Error). frames = instantanés tous les `every` pas (pas 0 inclus). */894 function wave1d(o) {895 o = o || {}; var s = pdeSetup("wave1d", o), c = pos("wave1d", o.c, "c"), C = c * s.dt / s.dx, C2 = C * C, i;896 if (C > 1 + 1e-12) fail("wave1d", "unstable: CFL number c*dt/dx = " + C + " must be <= 1");897 var prev = s.u, cur = prev.slice(), frames = [prev.slice()], times = [0];898 for (i = 1; i < s.n - 1; i++) cur[i] = prev[i] + 0.5 * C2 * (prev[i + 1] - 2 * prev[i] + prev[i - 1]); // premier pas : vitesse initiale nulle899 for (var k = 1; k <= s.steps; k++) {900 if (k % s.every === 0) { frames.push(cur.slice()); times.push(k * s.dt); }901 var nxt = cur.slice();902 for (i = 1; i < s.n - 1; i++) nxt[i] = 2 * cur[i] - prev[i] + C2 * (cur[i + 1] - 2 * cur[i] + cur[i - 1]);903 prev = cur; cur = nxt;904 }905 return { x: s.x, frames: frames, times: times, cfl: C, meta: meta("wave1d", { n: s.n, c: c, dx: s.dx, dt: s.dt, steps: s.steps, cfl: C }, "u_{tt}=c^2u_{xx},\\quad c\\,\\Delta t/\\Delta x\\le 1") };906 }907 /* Équation de la chaleur u_t = α u_xx, extrémités maintenues à leurs valeurs initiales (Dirichlet), schéma explicite FTCS ;908 stabilité : r = α·dt/dx² ≤ 1/2 (sinon Error). */909 function heat1d(o) {910 o = o || {}; var s = pdeSetup("heat1d", o), alpha = pos("heat1d", o.alpha, "alpha"), r = alpha * s.dt / (s.dx * s.dx);911 if (r > 0.5 + 1e-12) fail("heat1d", "unstable: r = alpha*dt/dx^2 = " + r + " must be <= 0.5");912 var cur = s.u, frames = [cur.slice()], times = [0];913 for (var k = 1; k <= s.steps; k++) {914 var nxt = cur.slice();915 for (var i = 1; i < s.n - 1; i++) nxt[i] = cur[i] + r * (cur[i + 1] - 2 * cur[i] + cur[i - 1]);916 cur = nxt;917 if (k % s.every === 0) { frames.push(cur.slice()); times.push(k * s.dt); }918 }919 return { x: s.x, frames: frames, times: times, r: r, meta: meta("heat1d", { n: s.n, alpha: alpha, dx: s.dx, dt: s.dt, steps: s.steps, r: r }, "u_t=\\alpha u_{xx},\\quad \\alpha\\,\\Delta t/\\Delta x^2\\le\\tfrac12") };920 }921922 root.SKN = {923 version: "1.0.0",924 rng: rng, linspace: linspace, range: range, clamp: clamp, lerp: lerp, sum: sum, mean: mean, variance: variance, std: std, covariance: covariance, correlation: correlation,925 quantile: quantile, histogram: histogram, cumsum: cumsum, dot: dot, matmul: matmul, transpose: transpose, matvec: matvec, identity: identity, solve: solve, cholesky: cholesky, inverse: inverse,926 erf: erf, erfc: erfc, logGamma: logGamma, normalPdf: normalPdf, normalCdf: normalCdf, normalInv: normalInv, lognormalPdf: lognormalPdf, studentTPdf: studentTPdf, uniformPdf: uniformPdf,927 exponentialPdf: exponentialPdf, binomialPmf: binomialPmf, poissonPmf: poissonPmf, sample: sample,928 derivative: derivative, integrate: integrate, rk4: rk4, euler: euler, vectorField: vectorField, streamline: streamline, gradientDescent: gradientDescent, surface: surface, project3d: project3d, rotate3d: rotate3d,929 softmax: softmax, attention: attention, positionalEncoding: positionalEncoding, tokenizeBpeDemo: tokenizeBpeDemo, mlpForward: mlpForward, mlpTrain: mlpTrain, datasets: datasets, pca2: pca2, cosineSimilarity: cosineSimilarity, kmeans: kmeans,930 compound: compound, presentValue: presentValue, annuityPv: annuityPv, npv: npv, irr: irr, blackScholes: blackScholes, impliedVol: impliedVol, volSurface: volSurface, gbmPaths: gbmPaths,931 valueAtRisk: valueAtRisk, var95: var95, expectedShortfall: expectedShortfall, portfolioStats: portfolioStats, sharpe: sharpe, minVariancePortfolio: minVariancePortfolio, tangencyPortfolio: tangencyPortfolio, efficientFrontier: efficientFrontier,932 nelsonSiegel: nelsonSiegel, yieldCurve: yieldCurve, orderBook: orderBook, matchMarketOrder: matchMarketOrder, ohlcFromPath: ohlcFromPath, rollingVolatility: rollingVolatility, garch11: garch11,933 projectile: projectile, pendulum: pendulum, springMass: springMass, nBodyStep: nBodyStep, wave1d: wave1d, heat1d: heat1d934 };935})();936