Files
havox/projects/pi_approximation.html
2026-03-16 18:03:17 +00:00

105 lines
2.2 KiB
HTML

<!DOCTYPE html>
<html>
<script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.min.js"></script>
<h1 id="PIbox"></h1>
<h2 id="percentage"></h2>
<style>
body {
font-family: Arial, sans-serif;
background: #fafafa;
margin: 20px;
text-align: center;
}
#container {
max-width: 900px;
margin: 0 auto;
}
h1,
h2,
p {
margin: 10px 0;
}
</style>
<div id="container">
<h1>Monte Carlo π Estimator</h1>
<p>
A small demonstation on how the Monte Carlo method can approximate the value of π
by randomly placing points inside a square and checking how many fall within
the inner circle. The closer the ratio gets to π/4, the more accurate
the estimation becomes.
</p>
<h2 id="PIbox"></h2>
<h3 id="percentage"></h3>
</div>
<script>
const r = 400;
var circleCount, total;
var x, y;
var calcPI;
var DisplayPI = "a";
const PI = 3.1415926535;
var BestPI = 50;
function setup() {
createCanvas(r * 2, r * 2);
background(0);
stroke(255, 0, 0);
strokeWeight(3);
noFill()
translate(width / 2, height / 2);
rectMode(CENTER);
rect(0, 0, r * 2, r * 2);
ellipse(0, 0, r * 2, r * 2);
circleCount = 0;
total = 0;
}
function draw() {
translate(width / 2, height / 2);
x = random(-r, r)
y = random(-r, r)
stroke(0, 255, 0)
total += 1
var d = dist(x, y, 0, 0)
if (d < r) {
circleCount += 1
stroke(0, 0, 255)
}
point(x, y);
calcPI = 4 * (circleCount / total);
if (abs(PI - calcPI) < abs(PI - BestPI)) {
DisplayPI = calcPI;
BestPI = calcPI;
var PIDisplay = document.getElementById("PIbox");
PIDisplay.innerHTML = DisplayPI;
var ErrorDisplay = document.getElementById("percentage");
var DisplayError = "a";
var Perror = (calcPI - PI) / PI
Perror *= 100;
DisplayError = nfc(Perror, 10);
ErrorDisplay.innerHTML = DisplayError + '%';
}
}
</script>
</html>