xxxxxxxxxx
42
// Approximating e
let approxE = 0;
let iterations = 0;
let div;
let history = [];
function setup() {
createCanvas(600, 400);
div = createDiv("").style("font-family: sans-serif; font-size: 30px");
}
function draw() {
background(0);
frameRate(5);
approxE += 1 / factorial(iterations);
iterations++;
history.push(approxE);
let spacing = width / history.length;
stroke(255, 0, 0);
strokeWeight(1);
noFill();
let ey = map(Math.E, 1, 3, height, 0);
line(0, ey, width, ey);
stroke(255);
strokeWeight(3);
beginShape();
for (let i = 0; i < history.length; i++) {
const x = i * spacing;
const y = map(history[i], 1, 3, height, 0);
vertex(x, y);
}
endShape();
div.html("e ≈ " + approxE);
}
function factorial(n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}