xxxxxxxxxx
56
// Daniel Shiffman
// http://codingtra.in
// Approximating Pi
// https://youtu.be/5cNnf_7e92Q
// https://thecodingtrain.com/CodingChallenges/095-approximating-pi.html
const r = 200;
let total = 0;
let squareCount = 0;
let recordPI = 0;
let resultP;
function setup() {
createCanvas(402, 402);
resultP = createP("Approximated Value:");
background(0);
translate(width / 2, height / 2);
stroke(255);
strokeWeight(4);
rectMode(CENTER);
noFill();
}
function draw() {
translate(width / 2, height / 2);
for (let i = 0; i < 1; i++) {
const x = random(-r, r);
const y = random(-r, r);
total++;
let sr = r * 0.5;
if (x > -sr && x < sr && y > -sr && y < sr) {
squareCount++;
stroke(240, 99, 164);
} else {
stroke(45, 197, 244);
}
strokeWeight(1);
point(x, y);
const pi = total / squareCount;
let recordDiff = Math.abs(4 - recordPI);
let diff = Math.abs(4 - pi);
if (diff < recordDiff) {
recordDiff = diff;
recordPI = pi;
resultP.html(`Approximated Value: ${recordPI}`);
}
}
}