xxxxxxxxxx
function setup() {
createCanvas(800, 800);
seed = Date.now();
randomSeed(seed);
background(0);
noLoop();
}
function draw() {
let total = 10000;
let circle = 0;
// Calcul de l'estimation de pi via la méthode de Monte Carlo
for (let i = 0; i < total; i++) {
let x = random(-1, 1);
let y = random(-1, 1);
let distance = x * x + y * y; // Distance au carré par rapport au centre
if (distance <= 1) {
circle++;
}
// Dessin des points
push();
translate(width / 2, height / 2);
scale(width / 2);
strokeWeight(0.015);
cr = random(0, 255);
if (distance <= 1) {
stroke(cr, cr, cr/2);
} else {
stroke(cr/2, cr, cr);
}
point(x, y);
pop();
}
// Estimation de pi
let piEstimate = 4 * (circle / total);
// Affichage de pi
push();
stroke(255);
strokeWeight(2);
fill(cr, cr, cr);
textAlign(CENTER);
textSize(36);
textStyle(ITALIC);
text("Monte-Carlo Pi", width/2,height-150);
textSize(72);
textStyle(NORMAL);
text(piEstimate, width/2,height-80);
strokeWeight(1);
textSize(12);
text("https://en.m.wikipedia.org/wiki/Monte_Carlo_method", width/2,height-20);
pop();
}
function keyTyped() {
if (key === "s" || key === "S") {
saveCanvas("fin.alg_monte-carlo_a-" + floor(random(100)), "png");
}
}