Code
viewof true_beta1 = {
const input = Inputs.range([-2, 2], {value: 0.7, step: 0.1, label: "True ฮฒโ:"});
['pointerdown','touchstart','mousedown','click','wheel','pointermove','touchmove']
.forEach(e => input.addEventListener(e, ev => ev.stopPropagation()));
return input;
}
viewof noise_sd = {
const input = Inputs.range([0.1, 3.0], {value: 0.8, step: 0.1, label: "Noise ฯ:"});
['pointerdown','touchstart','mousedown','click','wheel','pointermove','touchmove']
.forEach(e => input.addEventListener(e, ev => ev.stopPropagation()));
return input;
}
viewof n_reg = {
const input = Inputs.range([5, 60], {value: 20, step: 1, label: "n (obs):"});
['pointerdown','touchstart','mousedown','click','wheel','pointermove','touchmove']
.forEach(e => input.addEventListener(e, ev => ev.stopPropagation()));
return input;
}
// Seeded pseudo-random using LCG
rand_data = {
const seed = 42;
let s = seed;
const lcg = () => { s = (1664525 * s + 1013904223) >>> 0; return s / 4294967296; };
const nrand = () => {
const u = lcg(), v = lcg();
return Math.sqrt(-2*Math.log(u+1e-10)) * Math.cos(2*Math.PI*v);
};
const pts = [];
for (let i = 0; i < n_reg; i++) {
const x = (i / (n_reg - 1)) * 4 - 2;
const y = 1.0 + true_beta1 * x + noise_sd * nrand();
pts.push({x, y});
}
return pts;
}
// LS estimates
lsfit = {
const n = rand_data.length;
const xbar = rand_data.reduce((s, d) => s + d.x, 0) / n;
const ybar = rand_data.reduce((s, d) => s + d.y, 0) / n;
const Sxx = rand_data.reduce((s, d) => s + (d.x - xbar)**2, 0);
const Sxy = rand_data.reduce((s, d) => s + (d.x - xbar)*(d.y - ybar), 0);
const Syy = rand_data.reduce((s, d) => s + (d.y - ybar)**2, 0);
const b1 = Sxy / Sxx;
const b0 = ybar - b1 * xbar;
const SSE = Syy - b1 * Sxy;
const S2 = SSE / (n - 2);
const S = Math.sqrt(S2);
const r2 = 1 - SSE / Syy;
const t_stat = b1 / (S / Math.sqrt(Sxx));
return {b0, b1, S, S2, r2, t_stat, Sxx, SSE, n};
}
stats_html = html`<div style="background:#f0f4ff; padding:8px; border-radius:6px; font-size:0.93em; line-height:1.7;">
<strong>ฮฒฬโ = ${lsfit.b1.toFixed(3)}</strong> (true: ${true_beta1.toFixed(1)})<br>
<strong>ฮฒฬโ = ${lsfit.b0.toFixed(3)}</strong><br>
<strong>S = ${lsfit.S.toFixed(3)}</strong><br>
<strong>rยฒ = ${lsfit.r2.toFixed(3)}</strong><br>
<strong>t = ${lsfit.t_stat.toFixed(3)}</strong> (df = ${lsfit.n - 2})
</div>`;
md`${stats_html}`
