Repository Public
1import type { Locale } from "@/schema";2import { createRng, studentTQuantile } from "../core";3import { param, type SimDef } from "../types";4import { Chart, chartSpec } from "../ui/Chart";5import { fmt, fmtInt, fmtPct } from "../ui/format";6import { Readouts } from "../ui/Readouts";78export interface Interval { mean: number; sd: number; lo: number; hi: number; covers: boolean }9export interface CiModel {10 mu: number; sigma: number; n: number; m: number; level: number;11 /** Student-t critical value t_{(1+c)/2, n−1}. */12 critical: number;13 intervals: Interval[];14 /** Share of the m intervals that contain μ. */15 coverage: number;16 misses: number;17 meanWidth: number;18}1920/** m samples of size n from N(μ, σ²); each gives the t interval x̄ ± t·s/√n. */21export function simulateIntervals(o: { mu: number; sigma: number; n: number; m: number; level: number }, seed: number): CiModel {22 const rng = createRng(seed, "ci");23 const critical = studentTQuantile((1 + o.level) / 2, o.n - 1);24 const intervals: Interval[] = [];25 let hit = 0, width = 0;26 for (let j = 0; j < o.m; j++) {27 let s = 0, ss = 0;28 for (let i = 0; i < o.n; i++) { const x = rng.normal(o.mu, o.sigma); s += x; ss += x * x; }29 const mean = s / o.n;30 const sd = Math.sqrt(Math.max(0, (ss - o.n * mean * mean) / (o.n - 1)));31 const half = (critical * sd) / Math.sqrt(o.n);32 const covers = mean - half <= o.mu && o.mu <= mean + half;33 if (covers) hit++;34 width += 2 * half;35 intervals.push({ mean, sd, lo: mean - half, hi: mean + half, covers });36 }37 return { ...o, critical, intervals, coverage: hit / o.m, misses: o.m - hit, meanWidth: width / o.m };38}3940const TXT = {41 fr: { title: "Intervalles de confiance sur des échantillons répétés", x: "Échantillon", y: "Moyenne et intervalle", ok: "contient μ", miss: "manque μ", nominal: "Niveau nominal", emp: "Couverture observée", misses: "Intervalles qui manquent μ", crit: "Valeur critique t", width: "Largeur moyenne" },42 en: { title: "Confidence intervals over repeated samples", x: "Sample", y: "Mean and interval", ok: "contains μ", miss: "misses μ", nominal: "Nominal level", emp: "Observed coverage", misses: "Intervals missing μ", crit: "Critical value t", width: "Mean width" },43} as const;4445function CiView({ model: m, locale, idPrefix }: { model: CiModel; locale: Locale; idPrefix: string }) {46 const L = TXT[locale];47 const pts = (covers: boolean) => m.intervals.map((iv, i) => ({ iv, i })).filter((d) => d.iv.covers === covers).map(({ iv, i }) => ({ x: i + 1, y: iv.mean, lo: iv.lo, hi: iv.hi }));48 const chart = chartSpec({49 kind: "scatter", dataKind: "synthetic", title: L.title, xLabel: L.x, yLabel: L.y,50 series: [{ name: L.ok, tone: "blue", points: pts(true) }, { name: L.miss, tone: "red", points: pts(false) }],51 annotations: [{ y: m.mu, label: `μ = ${fmt(locale, m.mu, 2)}` }],52 });53 return (54 <>55 <Chart chart={chart} locale={locale} idPrefix={idPrefix} />56 <Readouts items={[57 { label: L.nominal, value: fmtPct(locale, m.level, 0) },58 { label: L.emp, value: fmtPct(locale, m.coverage, 1), tone: "blue" },59 { label: L.misses, value: `${fmtInt(locale, m.misses)} / ${fmtInt(locale, m.m)}`, tone: "red" },60 { label: L.crit, value: fmt(locale, m.critical, 3) },61 { label: L.width, value: fmt(locale, m.meanWidth, 3) },62 ]} />63 </>64 );65}6667export const confidenceInterval: SimDef<CiModel> = {68 kind: "confidence-interval",69 title: { fr: "Intervalles de confiance et couverture", en: "Confidence intervals and coverage" },70 description: {71 fr: "On tire $m$ échantillons de taille $n$ dans $\\mathcal{N}(\\mu, \\sigma^2)$ et on construit pour chacun l'intervalle de Student $\\bar{x} \\pm t\\, s/\\sqrt{n}$ ($\\sigma$ inconnu, estimé par $s$). À long terme, la proportion d'intervalles contenant $\\mu$ est égale au niveau de confiance ; sur $m$ échantillons seulement, la couverture observée fluctue autour de ce niveau.",72 en: "We draw $m$ samples of size $n$ from $\\mathcal{N}(\\mu, \\sigma^2)$ and build for each the Student interval $\\bar{x} \\pm t\\, s/\\sqrt{n}$ ($\\sigma$ unknown, estimated by $s$). In the long run the share of intervals containing $\\mu$ equals the confidence level; over only $m$ samples the observed coverage fluctuates around it.",73 },74 params: [75 param("n", "Taille d'échantillon n", "Sample size n", 2, 200, 1, 20),76 param("m", "Nombre d'échantillons m", "Number of samples m", 10, 100, 5, 50),77 param("level", "Niveau de confiance", "Confidence level", 0.5, 0.99, 0.01, 0.95),78 param("mu", "Moyenne vraie μ", "True mean μ", -5, 5, 0.5, 0),79 param("sigma", "Écart-type σ", "Standard deviation σ", 0.5, 5, 0.5, 1),80 ],81 stochastic: true,82 compute: (p, seed) => simulateIntervals({ mu: p.mu, sigma: p.sigma, n: Math.round(p.n), m: Math.round(p.m), level: p.level }, seed),83 View: CiView,84};85