Prompt specification
Build or customize the Three.js 3D scene "Sample-size interval-width comparison" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Sample-size interval-width comparison
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/sample-size-interval-width-comparison-x1806
Scene Description Prompt:
Sample-size interval-width comparison. Draw intervals from repeated normal-model samples of different sizes with known variance; compare width and realized coverage while keeping the underlying parameter fixed. Please build this with Three.js from cdnjs in one self-contained HTML file, using stylized solid shapes.
Working Three.js Starter (sample-size-interval-width-comparison-x1806):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Normal Confidence Interval Lab</title>
<style>
:root {
--bg: #edf1ec;
--panel: #f8faf6;
--ink: #183028;
--muted: #64766d;
--line: #d8e0da;
--green: #2a9d78;
--red: #e76f51;
--gold: #f4b942;
--blue: #335cff;
--shadow: 0 12px 34px rgba(24, 48, 40, 0.12);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input { font: inherit; }
#app {
display: grid;
grid-template-columns: 350px minmax(0, 1fr);
width: 100%;
height: 100%;
}
aside {
position: relative;
z-index: 5;
overflow-y: auto;
padding: 24px 22px 30px;
background: var(--panel);
border-right: 1px solid var(--line);
box-shadow: 6px 0 24px rgba(24, 48, 40, 0.05);
}
.eyebrow {
margin-bottom: 8px;
color: var(--green);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 27px;
line-height: 1.05;
letter-spacing: -0.035em;
}
.intro {
margin: 12px 0 20px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.formula {
margin: 0 0 20px;
padding: 13px 14px;
border: 1px solid #dbe5dd;
border-radius: 13px;
background: #eef5ef;
color: #29463a;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 12px;
line-height: 1.55;
}
.formula strong {
display: block;
margin-bottom: 3px;
color: var(--ink);
font-family: inherit;
}
.section-title {
margin: 23px 0 11px;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
color: var(--muted);
}
.field {
display: grid;
gap: 6px;
margin-bottom: 11px;
}
.field label,
.field-label {
color: #40574d;
font-size: 12px;
font-weight: 650;
}
.field input {
width: 100%;
min-width: 0;
padding: 10px 11px;
border: 1px solid var(--line);
border-radius: 10px;
outline: none;
background: #fff;
color: var(--ink);
font-size: 13px;
transition: border-color 120ms, box-shadow 120ms;
}
.field input:focus {
border-color: #82b79f;
box-shadow: 0 0 0 3px rgba(42, 157, 120, 0.11);
}
.field-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.n-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
}
.n-grid .field { margin-bottom: 0; }
.small-note {
margin: 8px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.actions {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
margin-top: 18px;
}
button {
border: 0;
cursor: pointer;
font-weight: 750;
}
.primary {
padding: 11px 14px;
border-radius: 11px;
background: var(--ink);
color: #fff;
box-shadow: 0 7px 16px rgba(24, 48, 40, 0.18);
}
.primary:hover { background: #27483c; }
.primary:disabled {
cursor: wait;
opacity: 0.6;
}
.secondary {
padding: 10px 12px;
border: 1px solid var(--line);
border-radius: 11px;
background: #fff;
color: var(--ink);
}
.secondary:hover { background: #f0f4ef; }
#status {
min-height: 18px;
margin-top: 9px;
color: var(--muted);
font-size: 11px;
text-align: center;
}
.shared-card {
padding: 13px 14px;
border: 1px solid #d7e1f8;
border-radius: 13px;
background: #f0f4ff;
}
.shared-card .row {
display: flex;
justify-content: space-between;
gap: 12px;
padding: 4px 0;
color: #4d5e77;
font-size: 12px;
}
.shared-card .row strong {
color: #20315a;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
.stat-card {
margin-top: 10px;
padding: 13px 14px;
border: 1px solid var(--line);
border-radius: 13px;
background: #fff;
box-shadow: 0 5px 15px rgba(24, 48, 40, 0.035);
}
.stat-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
}
.stat-head span {
font-size: 13px;
font-weight: 800;
}
.coverage {
color: var(--green);
font-size: 20px;
font-weight: 850;
letter-spacing: -0.03em;
}
.coverage.warn { color: #bb752b; }
.coverage-track {
position: relative;
height: 6px;
margin: 9px 0 11px;
overflow: hidden;
border-radius: 999px;
background: #e7ece8;
}
.coverage-fill {
height: 100%;
border-radius: inherit;
background: var(--green);
}
.coverage-fill.warn { background: #d9913d; }
.nominal {
position: absolute;
top: -2px;
bottom: -2px;
width: 1px;
background: #243b31;
opacity: 0.55;
}
.stat-grid {
display: grid;
grid-template-columns: 1fr auto;
gap: 5px 12px;
color: var(--muted);
font-size: 11px;
}
.stat-grid b {
color: var(--ink);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-weight: 700;
}
#viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: var(--bg);
}
canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
}
.scene-heading {
position: absolute;
top: 24px;
left: 28px;
z-index: 2;
max-width: 440px;
pointer-events: none;
}
.scene-heading .eyebrow {
margin-bottom: 7px;
color: #427d67;
}
.scene-heading h2 {
margin: 0;
font-size: clamp(21px, 2.4vw, 34px);
line-height: 1.03;
letter-spacing: -0.045em;
}
.scene-heading p {
max-width: 430px;
margin: 9px 0 0;
color: #60736a;
font-size: 12px;
line-height: 1.5;
}
.nominal-badge {
position: absolute;
top: 25px;
right: 25px;
z-index: 2;
padding: 9px 12px;
border: 1px solid rgba(51, 92, 255, 0.18);
border-radius: 999px;
background: rgba(248, 250, 255, 0.84);
color: #2949ae;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.05em;
box-shadow: var(--shadow);
pointer-events: none;
}
.legend {
position: absolute;
left: 25px;
bottom: 22px;
z-index: 3;
display: flex;
flex-wrap: wrap;
gap: 8px 14px;
max-width: calc(100% - 50px);
padding: 10px 13px;
border: 1px solid rgba(207, 218, 210, 0.9);
border-radius: 12px;
background: rgba(248, 250, 246, 0.88);
box-shadow: var(--shadow);
backdrop-filter: blur(8px);
color: #496056;
font-size: 11px;
pointer-events: none;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 6px;
white-space: nowrap;
}
.swatch {
width: 10px;
height: 10px;
border-radius: 3px;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.06);
}
.swatch.covered { background: var(--green); }
.swatch.missed { background: var(--red); }
.swatch.mean { background: var(--gold); border-radius: 50%; }
.swatch.truth { background: var(--blue); }
.depth-note {
position: absolute;
right: 24px;
bottom: 24px;
z-index: 2;
max-width: 250px;
color: #718178;
font-size: 10px;
line-height: 1.45;
text-align: right;
pointer-events: none;
}
#tooltip {
position: absolute;
z-index: 10;
display: none;
min-width: 190px;
padding: 10px 12px;
border: 1px solid rgba(207, 218, 210, 0.95);
border-radius: 10px;
background: rgba(255, 255, 255, 0.96);
box-shadow: var(--shadow);
color: var(--ink);
font-size: 11px;
line-height: 1.55;
pointer-events: none;
}
#tooltip strong {
display: block;
margin-bottom: 3px;
font-size: 12px;
}
#tooltip .ok { color: #1d805f; font-weight: 750; }
#tooltip .miss { color: #c85439; font-weight: 750; }
.camera-help {
position: absolute;
right: 25px;
bottom: 58px;
z-index: 2;
color: #7b8981;
font-size: 10px;
pointer-events: none;
}
@media (max-width: 820px) {
html, body { overflow: auto; }
#app {
grid-template-columns: 1fr;
grid-template-rows: minmax(390px, 46vh) minmax(500px, 54vh);
}
aside {
border-right: 0;
border-bottom: 1px solid var(--line);
}
.scene-heading {
top: 16px;
left: 17px;
}
.scene-heading p { display: none; }
.nominal-badge {
top: 16px;
right: 16px;
}
.legend {
left: 14px;
bottom: 13px;
}
.depth-note, .camera-help { display: none; }
}
</style>
</head>
<body>
<div id="app">
<aside>
<div class="eyebrow">Known-variance normal model</div>
<h1>Interval-width lab</h1>
<p class="intro">
Compare repeated confidence intervals for a normal population.
Every group uses the same true mean and variance; only the sample
size changes.
</p>
<div class="formula">
<strong>95% CI for μ with known σ²</strong>
x̄ ± 1.960 · σ / √n
</div>
<div class="section-title">Shared population</div>
<div class="field-row">
<div class="field">
<label for="trueMean">True mean μ</label>
<input id="trueMean" type="number" value="0.8" step="0.1" />
</div>
<div class="field">
<label for="variance">Known variance σ²</label>
<input id="variance" type="number" value="1" min="0.01" step="0.1" />
</div>
</div>
<p class="small-note">
These values are held fixed across all sample-size groups within a run.
</p>
<div class="section-title">Sample sizes</div>
<div class="n-grid">
<div class="field">
<label for="n1">n₁</label>
<input id="n1" type="number" value="25" min="5" max="2000" step="1" />
</div>
<div class="field">
<label for="n2">n₂</label>
<input id="n2" type="number" value="100" min="5" max="2000" step="1" />
</div>
<div class="field">
<label for="n3">n₃</label>
<input id="n3" type="number" value="400" min="5" max="2000" step="1" />
</div>
</div>
<div class="field-row" style="margin-top: 11px">
<div class="field">
<label for="repetitions">Repetitions / group</label>
<input id="repetitions" type="number" value="120" min="20" max="300" step="1" />
</div>
<div class="field">
<label for="seed">Random seed</label>
<input id="seed" type="number" value="2025" min="0" step="1" />
</div>
</div>
<div class="actions">
<button id="run" class="primary" type="button">Run comparison</button>
<button id="newSeed" class="secondary" type="button">New seed</button>
</div>
<div id="status" aria-live="polite"></div>
<div class="section-title">Fixed model in this run</div>
<div class="shared-card">
<div class="row">
<span>True parameter</span>
<strong id="sharedMu">μ = 0.80</strong>
</div>
<div class="row">
<span>Population variance</span>
<strong id="sharedVariance">σ² = 1.00</strong>
</div>
<div class="row">
<span>Nominal coverage</span>
<strong>95.0%</strong>
</div>
</div>
<div class="section-title">Realized comparison</div>
<div id="statsList"></div>
<p class="small-note" style="margin-top: 15px">
Each sample mean is drawn as
x̄ ~ Normal(μ, σ²/n), which is mathematically identical to averaging
n independent normal observations.
</p>
</aside>
<main id="viewport">
<div class="scene-heading">
<div class="eyebrow">Repeated confidence intervals</div>
<h2>One truth. Tighter intervals.</h2>
<p>
Each rod is one 95% confidence interval. A green interval covers
the fixed blue truth line; red intervals miss it.
</p>
</div>
<div class="nominal-badge">95% NOMINAL COVERAGE</div>
<div class="legend">
<span class="legend-item"><i class="swatch covered"></i>covered</span>
<span class="legend-item"><i class="swatch missed"></i>missed</span>
<span class="legend-item"><i class="swatch mean"></i>sample mean</span>
<span class="legend-item"><i class="swatch truth"></i>true μ</span>
</div>
<div class="camera-help">Drag: orbit · Shift/right-drag: pan · Wheel: zoom</div>
<div class="depth-note">
Repetition depth is ordered by sample mean for readability.
Hover an interval for details.
</div>
<div id="tooltip"></div>
<canvas id="scene" aria-label="3D comparison of confidence interval widths"></canvas>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (selector) => document.querySelector(selector);
const viewport = $("#viewport");
const canvas = $("#scene");
const tooltip = $("#tooltip");
const COLORS = {
covered: 0x2a9d78,
missed: 0xe76f51,
mean: 0xf4b942,
truth: 0x335cff,
axis: 0x7f9187,
text: 0x183028
};
const Z95 = 1.959963984540054;
const WORLD_HALF = 5.25;
const DEPTH_HALF = 4.75;
const GROUP_Y = [3.45, 0, -3.45];
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.03;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xedf1ec);
scene.fog = new THREE.Fog(0xedf1ec, 24, 48);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const dynamicRoot = new THREE.Group();
scene.add(dynamicRoot);
let pickables = [];
let currentModel = null;
// Lighting and a simple solid floor.
scene.add(new THREE.HemisphereLight(0xffffff, 0x81968c, 2.1));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.4);
keyLight.position.set(-8, 14, 10);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -15;
keyLight.shadow.camera.right = 15;
keyLight.shadow.camera.top = 15;
keyLight.shadow.camera.bottom = -15;
keyLight.shadow.normalBias = 0.035;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0xc9dcff, 0.65);
fillLight.position.set(12, 6, -10);
scene.add(fillLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(50, 50),
new THREE.MeshStandardMaterial({
color: 0xe4eae3,
roughness: 0.97,
metalness: 0
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -6.05;
floor.receiveShadow = true;
scene.add(floor);
// Custom camera controls.
const cameraState = {
theta: 0.33,
phi: 1.04,
radius: 19.5,
target: new THREE.Vector3(0, -0.15, 0)
};
function updateCamera() {
const { theta, phi, radius, target } = cameraState;
const sinPhi = Math.sin(phi);
camera.position.set(
target.x + radius * sinPhi * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + radius * sinPhi * Math.cos(theta)
);
camera.lookAt(target);
}
function resetCamera() {
cameraState.theta = 0.33;
cameraState.phi = 1.04;
cameraState.radius = 19.5;
cameraState.target.set(0, -0.15, 0);
updateCamera();
}
function panCamera(dx, dy) {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3()
.crossVectors(forward, new THREE.Vector3(0, 1, 0))
.normalize();
const amount = cameraState.radius * 0.0015;
cameraState.target
.addScaledVector(right, -dx * amount)
.addScaledVector(new THREE.Vector3(0, 1, 0), dy * amount);
cameraState.target.x = THREE.MathUtils.clamp(cameraState.target.x, -6, 6);
cameraState.target.y = THREE.MathUtils.clamp(cameraState.target.y, -3, 3);
cameraState.target.z = THREE.MathUtils.clamp(cameraState.target.z, -5, 5);
}
let dragging = false;
let dragButton = 0;
let lastX = 0;
let lastY = 0;
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
dragButton = event.button;
lastX = event.clientX;
lastY = event.clientY;
tooltip.style.display = "none";
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (dragging) {
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
lastX = event.clientX;
lastY = event.clientY;
if (event.shiftKey || dragButton === 2) {
panCamera(dx, dy);
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.28,
1.46
);
}
updateCamera();
} else {
updateHover(event);
}
});
function endDrag(event) {
dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener("pointerleave", () => {
tooltip.style.display = "none";
});
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
10,
38
);
updateCamera();
}, { passive: false });
canvas.addEventListener("dblclick", resetCamera);
// Reproducible pseudo-random generator and normal distribution.
function mulberry32(seed) {
return function () {
let t = seed += 0x6d2b79f5;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function standardNormal(rng) {
let u = 0;
let v = 0;
while (u === 0) u = rng();
while (v === 0) v = rng();
return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
}
function createLabel(lines, accent = "#183028", width = 768, height = 220) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = width;
labelCanvas.height = height;
const context = labelCanvas.getContext("2d");
context.clearRect(0, 0, width, height);
const radius = 28;
const x = 8;
const y = 8;
const w = width - 16;
const h = height - 16;
context.beginPath();
context.moveTo(x + radius, y);
context.lineTo(x + w - radius, y);
context.quadraticCurveTo(x + w, y, x + w, y + radius);
context.lineTo(x + w, y + h - radius);
context.quadraticCurveTo(x + w, y + h, x + w - radius, y + h);
context.lineTo(x + radius, y + h);
context.quadraticCurveTo(x, y + h, x, y + h - radius);
context.lineTo(x, y + radius);
context.quadraticCurveTo(x, y, x + radius, y);
context.closePath();
context.fillStyle = "rgba(250, 252, 248, 0.92)";
context.fill();
context.strokeStyle = "rgba(155, 175, 163, 0.55)";
context.lineWidth = 3;
context.stroke();
context.fillStyle = accent;
context.textAlign = "center";
context.textBaseline = "middle";
if (lines.length === 1) {
context.font = "700 56px system-ui, sans-serif";
context.fillText(lines[0], width / 2, height / 2 + 2);
} else {
context.font = "800 60px system-ui, sans-serif";
context.fillText(lines[0], width / 2, height * 0.38);
context.fillStyle = "#64766d";
context.font = "600 35px ui-monospace, monospace";
context.fillText(lines[1], width / 2, height * 0.72);
}
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false,
fog: false
});
const sprite = new THREE.Sprite(material);
sprite.renderOrder = 20;
return sprite;
}
function addLabel(lines, position, scale, accent) {
const label = createLabel(lines, accent);
label.position.set(...position);
label.scale.set(...scale);
dynamicRoot.add(label);
return label;
}
function rodBetween(a, b, radius, material) {
const start = new THREE.Vector3(...a);
const end = new THREE.Vector3(...b);
const direction = end.clone().sub(start);
const length = direction.length();
const geometry = new THREE.CylinderGeometry(
radius,
radius,
length,
12
);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
dynamicRoot.add(mesh);
return mesh;
}
function disposeDynamic() {
const geometries = new Set();
const materials = new Set();
const textures = new Set();
dynamicRoot.traverse((object) => {
if (object.geometry) geometries.add(object.geometry);
if (object.material) {
const list = Array.isArray(object.material)
? object.material
: [object.material];
for (const material of list) {
materials.add(material);
if (material.map) textures.add(material.map);
}
}
});
for (const geometry of geometries) geometry.dispose();
for (const texture of textures) texture.dispose();
for (const material of materials) material.dispose();
dynamicRoot.clear();
pickables = [];
}
function simulate() {
const trueMean = Number($("#trueMean").value);
const variance = Number($("#variance").value);
const repetitions = Math.round(Number($("#repetitions").value));
const sampleSizes = [
Math.round(Number($("#n1").value)),
Math.round(Number($("#n2").value)),
Math.round(Number($("#n3").value))
];
const seed = Number($("#seed").value) >>> 0;
if (!Number.isFinite(trueMean) || trueMean < -100 || trueMean > 100) {
throw new Error("The true mean must be a finite number.");
}
if (!Number.isFinite(variance) || variance <= 0 || variance > 10000) {
throw new Error("The known variance must be greater than zero.");
}
if (!Number.isInteger(repetitions) || repetitions < 20 || repetitions > 300) {
throw new Error("Repetitions must be an integer from 20 to 300.");
}
if (sampleSizes.some(n => !Number.isInteger(n) || n < 5 || n > 2000)) {
throw new Error("Sample sizes must be integers from 5 to 2000.");
}
const sigma = Math.sqrt(variance);
const rng = mulberry32(seed);
const groups = sampleSizes.map((n, groupIndex) => {
const standardError = sigma / Math.sqrt(n);
const halfWidth = Z95 * standardError;
const samples = [];
for (let draw = 0; draw < repetitions; draw++) {
const mean = trueMean + standardError * standardNormal(rng);
const lower = mean - halfWidth;
const upper = mean + halfWidth;
const covered = lower <= trueMean && trueMean <= upper;
samples.push({
groupIndex,
n,
draw,
mean,
lower,
upper,
covered
});
}
const coveredCount = samples.filter(s => s.covered).length;
const meanWidth = samples.reduce(
(sum, sample) => sum + (sample.upper - sample.lower),
0
) / repetitions;
return {
groupIndex,
n,
standardError,
halfWidth,
expectedWidth: 2 * halfWidth,
meanWidth,
coverage: coveredCount / repetitions,
coveredCount,
missedCount: repetitions - coveredCount,
samples
};
});
return {
trueMean,
variance,
sigma,
repetitions,
seed,
nominalCoverage: 0.95,
groups
};
}
function buildVisualization(model) {
disposeDynamic();
currentModel = model;
const largestGroup = model.groups.reduce((a, b) =>
a.halfWidth + 3.5 * a.standardError >
b.halfWidth + 3.5 * b.standardError ? a : b
);
const halfSpan = Math.max(
1.15,
largestGroup.halfWidth + 3.5 * largestGroup.standardError
);
const xScale = WORLD_HALF / halfSpan;
const axisMaterial = new THREE.MeshStandardMaterial({
color: COLORS.axis,
roughness: 0.8
});
const truthMaterial = new THREE.MeshStandardMaterial({
color: COLORS.truth,
roughness: 0.48,
metalness: 0.03
});
const trayColors = [0xe0e9e1, 0xe5ebe5, 0xe1e8e2];
const trayLipColors = [0xc8d5cb, 0xced8cf, 0xc9d4ca];
model.groups.forEach((group, groupIndex) => {
const groupY = GROUP_Y[groupIndex];
// Solid tray underneath each group.
const tray = new THREE.Mesh(
new THREE.BoxGeometry(10.65, 0.08, 10.15),
new THREE.MeshStandardMaterial({
color: trayColors[groupIndex],
roughness: 0.95
})
);
tray.position.set(0, groupY - 1.08, 0);
tray.receiveShadow = true;
dynamicRoot.add(tray);
const lip = new THREE.Mesh(
new THREE.BoxGeometry(10.65, 0.19, 0.09),
new THREE.MeshStandardMaterial({
color: trayLipColors[groupIndex],
roughness: 0.88
})
);
lip.position.set(0, groupY - 0.99, 5.08);
lip.castShadow = true;
dynamicRoot.add(lip);
// The shared true mean is a blue rail running through each group.
rodBetween(
[0, groupY + 0.10, -DEPTH_HALF],
[0, groupY + 0.10, DEPTH_HALF],
0.026,
truthMaterial
);
const truthDot = new THREE.Mesh(
new THREE.SphereGeometry(0.085, 18, 12),
new THREE.MeshStandardMaterial({
color: COLORS.truth,
roughness: 0.42
})
);
truthDot.position.set(0, groupY + 0.10, DEPTH_HALF);
truthDot.castShadow = true;
dynamicRoot.add(truthDot);
addLabel(
[`n = ${group.n}`, `half-width ${group.halfWidth.toFixed(3)}`],
[-5.0, groupY + 0.56, -4.85],
[2.0, 0.58, 1],
"#183028"
);
// Sorting by sample mean makes the repeated interval cloud legible.
const orderedSamples = [...group.samples].sort((a, b) => a.mean - b.mean);
const intervalGeometry = new THREE.CylinderGeometry(0.027, 0.027, 1, 10);
intervalGeometry.rotateZ(Math.PI / 2);
const intervalMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.56,
metalness: 0.02
});
const intervalMesh = new THREE.InstancedMesh(
intervalGeometry,
intervalMaterial,
orderedSamples.length
);
const capGeometry = new THREE.CylinderGeometry(0.052, 0.052, 0.23, 12);
const capMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.52,
metalness: 0.02
});
const capMesh = new THREE.InstancedMesh(
capGeometry,
capMaterial,
orderedSamples.length
);
const meanGeometry = new THREE.SphereGeometry(0.072, 16, 12);
const meanMaterial = new THREE.MeshStandardMaterial({
color: COLORS.mean,
roughness: 0.42,
metalness: 0.04
});
const meanMesh = new THREE.InstancedMesh(
meanGeometry,
meanMaterial,
orderedSamples.length
);
intervalMesh.castShadow = true;
capMesh.castShadow = true;
meanMesh.castShadow = true;
const dummy = new THREE.Object3D();
const color = new THREE.Color();
orderedSamples.forEach((sample, index) => {
const z = model.repetitions === 1
? 0
: -DEPTH_HALF + (index / (model.repetitions - 1)) * (2 * DEPTH_HALF);
const lowerX = (sample.lower - model.trueMean) * xScale;
const upperX = (sample.upper - model.trueMean) * xScale;
const meanX = (sample.mean - model.trueMean) * xScale;
const length = upperX - lowerX;
const y = groupY + 0.10;
dummy.position.set((lowerX + upperX) / 2, y, z);
dummy.quaternion.identity();
dummy.scale.set(length, 1, 1);
dummy.updateMatrix();
intervalMesh.setMatrixAt(index, dummy.matrix);
color.setHex(sample.covered ? COLORS.covered : COLORS.missed);
intervalMesh.setColorAt(index, color);
dummy.position.set(lowerX, y, z);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
capMesh.setMatrixAt(index, dummy.matrix);
capMesh.setColorAt(index, color);
dummy.position.set(upperX, y, z);
dummy.updateMatrix();
capMesh.setMatrixAt(index, dummy.matrix);
capMesh.setColorAt(index, color);
dummy.position.set(meanX, y + 0.025, z);
dummy.updateMatrix();
meanMesh.setMatrixAt(index, dummy.matrix);
});
intervalMesh.instanceMatrix.needsUpdate = true;
capMesh.instanceMatrix.needsUpdate = true;
meanMesh.instanceMatrix.needsUpdate = true;
if (intervalMesh.instanceColor) intervalMesh.instanceColor.needsUpdate = true;
if (capMesh.instanceColor) capMesh.instanceColor.needsUpdate = true;
intervalMesh.userData.samples = orderedSamples;
capMesh.userData.samples = orderedSamples;
intervalMesh.frustumCulled = false;
capMesh.frustumCulled = false;
meanMesh.frustumCulled = false;
dynamicRoot.add(intervalMesh, capMesh, meanMesh);
pickables.push(intervalMesh, capMesh);
});
// Shared parameter axis.
const axisY = -5.30;
const axisZ = 5.05;
rodBetween(
[-WORLD_HALF, axisY, axisZ],
[WORLD_HALF, axisY, axisZ],
0.025,
axisMaterial
);
const tickCount = 8;
for (let i = 0; i <= tickCount; i++) {
const fraction = i / tickCount;
const parameterDelta = -halfSpan + fraction * 2 * halfSpan;
const x = parameterDelta * xScale;
rodBetween(
[x, axisY, axisZ - 0.15],
[x, axisY, axisZ + 0.15],
0.018,
axisMaterial
);
addLabel(
[(model.trueMean + parameterDelta).toFixed(1)],
[x, axisY - 0.38, axisZ],
[0.72, 0.25, 1],
"#52675c"
);
}
addLabel(
["sample mean x̄"],
[WORLD_HALF - 0.35, axisY - 0.40, axisZ],
[1.75, 0.27, 1],
"#52675c"
);
addLabel(
[`true μ = ${model.trueMean.toFixed(2)}`],
[0, 4.65, 4.85],
[2.05, 0.36, 1],
"#2949ae"
);
updateStats(model);
updateSharedReadout(model);
}
function updateSharedReadout(model) {
$("#sharedMu").textContent = `μ = ${model.trueMean.toFixed(2)}`;
$("#sharedVariance").textContent = `σ² = ${model.variance.toFixed(2)}`;
}
function updateStats(model) {
const statsList = $("#statsList");
statsList.innerHTML = model.groups.map(group => {
const coveragePercent = group.coverage * 100;
const difference = Math.abs(coveragePercent - 95);
const warning = difference > 5;
return `
<div class="stat-card">
<div class="stat-head">
<span>n = ${group.n}</span>
<strong class="coverage ${warning ? "warn" : ""}">
${coveragePercent.toFixed(1)}%
</strong>
</div>
<div class="coverage-track">
<div
class="coverage-fill ${warning ? "warn" : ""}"
style="width:${Math.min(100, coveragePercent)}%"
></div>
<i class="nominal" style="left:95%"></i>
</div>
<div class="stat-grid">
<span>Expected width</span><b>${group.expectedWidth.toFixed(3)}</b>
<span>Mean realized width</span><b>${group.meanWidth.toFixed(3)}</b>
<span>Covered / missed</span><b>${group.coveredCount} / ${group.missedCount}</b>
<span>Standard error</span><b>${group.standardError.toFixed(3)}</b>
</div>
</div>
`;
}).join("");
}
// Hover details for the instanced intervals.
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function updateHover(event) {
if (!pickables.length) return;
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(pickables, false);
if (!intersections.length) {
tooltip.style.display = "none";
return;
}
const hit = intersections[0];
const samples = hit.object.userData.samples;
const sample = samples?.[hit.instanceId];
if (!sample) {
tooltip.style.display = "none";
return;
}
tooltip.innerHTML = `
<strong>n = ${sample.n} · draw ${sample.draw + 1}</strong>
x̄ = ${sample.mean.toFixed(4)}<br>
CI = [${sample.lower.toFixed(4)}, ${sample.upper.toFixed(4)}]<br>
<span class="${sample.covered ? "ok" : "miss"}">
${sample.covered ? "Covers the true μ" : "Misses the true μ"}
</span>
`;
const viewportRect = viewport.getBoundingClientRect();
const x = event.clientX - viewportRect.left + 14;
const y = event.clientY - viewportRect.top + 14;
tooltip.style.left = `${Math.min(x, viewportRect.width - 220)}px`;
tooltip.style.top = `${Math.min(y, viewportRect.height - 120)}px`;
tooltip.style.display = "block";
}
function runComparison() {
const button = $("#run");
button.disabled = true;
$("#status").textContent = "Drawing repeated intervals…";
setTimeout(() => {
try {
const model = simulate();
buildVisualization(model);
$("#status").textContent =
`${model.repetitions} repetitions per group · seed ${model.seed}`;
} catch (error) {
$("#status").textContent = error.message;
} finally {
button.disabled = false;
}
}, 35);
}
$("#run").addEventListener("click", runComparison);
$("#newSeed").addEventListener("click", () => {
const seed = Math.floor(Math.random() * 4294967295);
$("#seed").value = seed;
runComparison();
});
function resize() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(viewport);
resize();
resetCamera();
runComparison();
renderer.setAnimationLoop(() => {
updateCamera();
renderer.render(scene, camera);
});
</script>
</body>
</html>
```