xxxxxxxxxx
83
/*
Title: Estimating PI value from possibility of two random number being coprime and plotting them on graph.
Author: PhoenixCreation(https://github.com/PhoenixCreation)
Original sketch: https://editor.p5js.org/codingtrain/sketches/FiOG6uajS
Referenace Video: https://youtu.be/EvS_a921dBo
Issues:
1. This uses avearge as a final reusult which may not be the most efficient way.
2. It runs for too long if your screen width is very big.(line 58)
3. It uses JavaScript's inbuilt Math.random() method for random number generation.(line 42) Because of that the final results and progress varies each time you run the sketch.
*/
let coprimeCount = 0;
let total = 0;
let pies = []; // Array to store all calculated PI values from each iteration
function setup() {
createCanvas(windowWidth, windowHeight);
// creating a common graph layout
background(0);
strokeWeight(2);
stroke(255)
line(40, 0, 40, height); // Vertical graph line - Y axis
line(40, height / 2, width, height / 2); // Horizontal graph line - X axis
strokeWeight(1);
fill(255);
stroke(0)
text("3.14", 0, height / 2) // Middle value
stroke(255, 0, 0);
strokeWeight(10)
point(width - 125, 50) // Indiacators on top right corner
stroke(255, 255, 0)
point(width - 125, 75)
noStroke()
fill(255)
text(" - Current PI", width - 115, 52.5)
text(" - Average PI", width - 115, 77.5)
}
function draw() {
// Calculate probability 500 random pairs for each iteration
for (let n = 0; n < 500; n++) {
var a = Math.floor(Math.random() * 1000000) + 1;
var b = Math.floor(Math.random() * 1000000) + 1;
total++;
if (gcd(a, b) === 1) {
coprimeCount++;
}
}
var pie = sqrt(6 * total / coprimeCount); // Main equation
pies.push(pie); // Add to the array to keep track of all
var currentPI = pies.reduce((acc, current) => acc + current, 0) / pies.length; // Calculate the average of PI values in `pies` array
stroke(0)
text("current PI:" + nf(pie, 1, 6), 100, 10); // show the current PI value on top
strokeWeight(3)
// Continue calculating till you reach the right side of the canvas
if (40 + pies.length / 2 < width - 40) {
stroke(255, 255, 0);
point(40 + pies.length / 2, height / 2 - ((currentPI - Math.PI) * 10000)); // draw a yellow point for average value
stroke(255, 0, 0);
point(40 + pies.length / 2, height / 2 - ((pie - Math.PI) * 10000)); // draw a red point for current PI value
} else {
// Now stop calculating and display results
noStroke();
textSize(24);
text(`Original Value of PI: ${Math.PI}`, 100, 50)
text(`Derived Value of PI: ${currentPI}`, 100, 100)
text(`Difference between values: ${currentPI - Math.PI}`, 100, 150)
noLoop(); // No more iterations of draw loop
}
}
/* Function to calculate GCD from Euclid's Algorithm */
function gcd(a, b) {
let r = a % b;
if (r == 0) {
return b;
} else {
return gcd(b, r);
}
}