-
-
Save Lytol/4d63000529c1c957aa5d178fd3280697 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 + ...) | |
function* pi() { | |
let n = 1; | |
let series = 0; | |
while(true) { | |
next = 1/(n*2-1) | |
if (n % 2 == 0) { | |
next = -next | |
} | |
series += next | |
yield [4*series, n++] | |
} | |
} | |
const roundPi = (scale) => { | |
const target = Math.PI.toFixed(scale) | |
const piGenerator = pi() | |
for(const [value, iteration] of piGenerator) { | |
const rounded = value.toFixed(scale) | |
if (rounded === target) { | |
return [rounded, iteration] | |
} | |
} | |
} | |
for (let i = 1; i <= 5; i++) { | |
const [value, iterations] = roundPi(i) | |
console.log(`Value: ${value} / Iterations: ${iterations}`) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment