Skip to content

Instantly share code, notes, and snippets.

@ggrumbley
Last active March 18, 2021 00:05
Show Gist options
  • Save ggrumbley/d2ae78fd40a9b09847974d6083ccfead to your computer and use it in GitHub Desktop.
Save ggrumbley/d2ae78fd40a9b09847974d6083ccfead to your computer and use it in GitHub Desktop.
// Define a method that rounds pi to a specified decimal place
// Return Pi and how many iterations of the following formula that it took to accomplish
// pi = 4 * (1 – 1/3 + 1/5 – 1/7 + ...)
const calcPi = (scale = 2) => {
const piTarget = Number(Math.PI).toFixed(scale);
let piAnswer;
let accum;
let denominator = 3;
let index = 0;
while (piAnswer !== piTarget) {
if (index === 0) {
accum = 1 - (1 / denominator);
} else {
let isEven = index % 2;
denominator += 2;
if(isEven === 0) {
accum -= (1 / denominator);
} else {
accum += (1 / denominator);
}
}
index++;
piAnswer = Number(4 * accum).toFixed(scale);
}
return [piAnswer, index];
};
const test0 = calcPi(0);
const test1 = calcPi(1);
const test2 = calcPi(2);
const test3 = calcPi(3);
const test4 = calcPi(4);
const test5 = calcPi(5);
console.log(test0);
console.log(test1);
console.log(test2);
console.log(test3);
console.log(test4);
console.log(test5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment