xxxxxxxxxx
114
/* Happy Pi day 2021!!
* Calculate an approximation of pi by
* increasing the sides of a regular polygon.
* P/(2*apothem) is approx pi
* On pi/2021
* by @ajuancer (juancer.me)
*/
let sideL = 60; // Side length.
let sideNo = 3; // no of sides
// With sideL = 1 and sideNo =10 000, the obtained value of
// pi is 3.1415926(...)
function setup() {
createCanvas(900, 900);
rectMode(CENTER);
let button = createButton("Show info");
button.position(30, 150);
button.mousePressed(() => {
if (document.getElementById("intro").style.display == "none") {
document.getElementById("intro").style.display = "block";
button.elt.innerText = "Hide info";
} else {
document.getElementById("intro").style.display = "none";
button.elt.innerText = "Show info";
}
});
}
function draw() {
background(220);
push();
translate(width / 2, height / 2);
[ap, per, iAngle] = polygon(0, 0, sideL, sideNo);
textSize(20);
text(`Perimeter: ${per}`, -width / 2 + 32, -height / 2 + 32);
text(
`Apothem (approx): ${round(ap, 5)}`,
-width / 2 + 32,
-height / 2 + 32 * 2
);
text(
`Interior angle (approx): ${round(iAngle, 5)}`,
-width / 2 + 32,
-height / 2 + 32 * 3
);
// Get pi
calcPi = sideNo * sin(iAngle / 2);
// Compare results.
fixedDecimals = {};
strCalcPi = calcPi.toString();
const PI_STRING = PI.toString();
for (i = 1; i < 14; i++) {
if (
strCalcPi.substring(0, i).localeCompare(PI_STRING.substring(0, i)) != 0
) {
fixedDecimals.common = strCalcPi.substring(0, i - 1);
fixedDecimals.diff = strCalcPi.substring(i);
break;
}
}
// Write pi
text("Calculated PI:", -width / 2 + 32, -height / 2 + 32 * 4);
fill(33, 203, 103);
text(
fixedDecimals.common,
-width / 2 + 32 + textWidth("Calculated PI: "),
-height / 2 + 32 * 4
);
fill(258, 51, 51);
text(
fixedDecimals.diff,
-width / 2 +
32 +
textWidth("Calculated PI: ") +
textWidth(fixedDecimals.common),
-height / 2 + 32 * 4
);
fill(255, 255, 255);
pop();
frameRate(10)
if (sideNo < 100) {
sideNo++;
sideL *= 0.99999
} else if (sideNo<300){
sideNo++;
sideL *= 0.995
}
}
// Based on polygon() of
// www.p5js.org/examples/form-regular-polygon.html
function polygon(x, y, side, npoints) {
let angle = TWO_PI / npoints;
let radius = side / (2 * sin(angle));
beginShape(TRIANGLE_FAN);
vertex(0, 0);
for (let a = 0; a < TWO_PI + angle; a += angle) {
let sx = x + cos(a) * radius;
let sy = y + sin(a) * radius;
vertex(sx, sy);
}
endShape(CLOSE);
let ap = side / (tan(angle / 2) * 2);
return [ap, npoints * side, angle];
}