← BACK TO THE NOTEBOOK

FIELD NOTES / math

[Sample] Math, code & small explosions

Abstract orbital curves and a bright circular marker, specimen 3

A circle inside a square #

Imagine throwing points at a square from −1-1 to 11 on each axis. A point lands inside the unit circle when x2+y2≤1x^2+y^2\leq1.

The ratio of areas gives us an estimate:

π≈4⋅NinsideNtotal\pi \approx 4 \cdot \frac{N_{\text{inside}}}{N_{\text{total}}}

A tiny simulation #

function estimatePi(samples = 100_000) {
  let inside = 0;
  for (let i = 0; i < samples; i++) {
    const x = Math.random() * 2 - 1;
    const y = Math.random() * 2 - 1;
    if (x * x + y * y <= 1) inside++;
  }
  return (4 * inside) / samples;
}

Read the result carefully #

More samples usually improve the estimate, but randomness does not promise a perfectly smooth journey. The typical error shrinks on the order of 1/N1/\sqrt{N}.1

Keep a record #

Run the function a few times with different sample counts. Note the spread, not just the result closest to the value you expected.

Follow the next question #

What would change if the points were not uniformly distributed? What would you measure to detect that? An experiment becomes useful when it creates a better question.

Footnotes #

  1. This is a statistical rule of thumb for independent samples, not a guarantee for any single run. ↩

⊕ END OF ENTRY. KEEP WONDERING.