Hello folks!
It is never to late for Pi!
// Monte Carlo Pi
// glv
// 2026-03-19
// Reference:
// https://en.wikipedia.org/wiki/Monte_Carlo_method
// The exact math:
// Area of circle: PI*r*r
// Area of square: 2*r * 2*r = 4*r*r
// Area of circle/Area of square = (PI*r*r)/(4*r*r) = PI/4
// PI = 4*(PI*r*r)/(4*r*r)
// The code does not use geometric area directly.
// It uses the ratio of random points in those regions
// to statistically estimate pi.
int numPoints = 5000;
float r = 200;
float r2, rr;
float w2, h2;
int inCircle = 0;
int counter = 0;
void setup()
{
size(500, 550, P2D);
background(0);
rr = r*r;
r2 = r*2;
w2 = width/2;
h2 = height/2;
resetRun();
}
void resetRun()
{
push();
translate(w2, h2);
background(0);
strokeWeight(2);
stroke(128);
fill(0);
rectMode(CENTER);
rect(0, 0, r2, r2);
ellipseMode(CENTER);
circle(0, 0, r2);
pop();
inCircle = 0;
counter = 0;
}
void draw()
{
if (counter >= numPoints)
{
resetRun();
return;
}
// Plot
float x = random(-r, r);
float y = random(-r, r);
float rCol = 128 + random(128);
if (x*x + y*y < rr)
{
stroke(0, rCol, rCol);
inCircle++;
}
else
stroke(255, 0, 0);
strokeWeight(3);
point(x+w2, y+h2);
counter++;
// HUD Overlay (Heads Up Display)
textAlign(LEFT, CENTER);
textSize(36);
fill(0); // Change to 128 to see where it is
noStroke();
rectMode(CORNER);
rect(0, 0, width, 60);
rect(0, height - 60, width, 60);
float mcPi = 4.0*inCircle/counter;
fill(255, 255, 0);
String s1 = "Monte Carlo π : " + " " + nfs(mcPi, 1, 5);
float xt = textWidth(s1);
text(s1, (width-xt)/2, 30);
String s2 = "Total Points: " + " " + str(counter);
float xt2 = textWidth(s2);
text(s2, (width-xt2)/2, height-35);
//println(counter, inCircle, mcPi);
}
void mousePressed()
{
resetRun();
}
References:
:)
