Skip to content

Instantly share code, notes, and snippets.

@ivarvong
Created March 14, 2023 15:44
Show Gist options
  • Save ivarvong/c05132421903424ed5cd018cfb56946e to your computer and use it in GitHub Desktop.
Save ivarvong/c05132421903424ed5cd018cfb56946e to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Estimating π</title>
<meta property="og:image" content="https://pi.ivarvong.repl.co/screenshot.jpg" />
<style>
html,
body {
background: #000;
margin: 0;
padding: 0;
color: #fff;
font-family: "SF Mono", "Monaco", "Inconsolata", "Fira Mono", "Droid Sans Mono", "Source Code Pro", monospace;
font-size: 30px;
overflow: hidden;
}
canvas {
width: calc(min(100vw, 100vh));
height: calc(min(100vw, 100vh));
}
</style>
</head>
<body>
<div style="display: grid; grid-template-columns: 1fr; grid-template-rows: 1fr;">
<canvas id="canvas" width="1000" height="1000" style="grid-area: 1/1/1/1; z-index: 1;"></canvas>
<div style="grid-area: 1/1/1/1; z-index: 2; padding: 30px;">
<div id="hits"></div>
<div id="pi"></div>
</div>
</div>
<script>
let hits = 0;
let n = 0;
let iterations = 100;
try {
const params = new URLSearchParams(window.location.search);
const candidate = parseInt(params.get("iterations"), 10);
if (candidate > 0) {
iterations = candidate;
}
} catch (e) {
console.error(e);
}
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const $pi = document.getElementById('pi');
const $hits = document.getElementById('hits');
function loop() {
for (let i = 0; i < iterations; i += 1) {
const x = Math.random();
const y = Math.random();
n += 1;
if (x * x + y * y <= 1) {
hits += 1;
ctx.fillStyle = "#ff294c";
} else {
ctx.fillStyle = "#000000";
}
ctx.fillRect(x * 1000, y * 1000, 1, 1);
}
$pi.innerText = `pi=${4 * hits / n}`;
$hits.innerText = `n=${n}`;
requestAnimationFrame(loop);
}
loop();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment