Skip to content

Instantly share code, notes, and snippets.

@Lytol
Forked from ggrumbley/pi.js
Last active March 17, 2021 23:53
Show Gist options
  • Save Lytol/4d63000529c1c957aa5d178fd3280697 to your computer and use it in GitHub Desktop.
Save Lytol/4d63000529c1c957aa5d178fd3280697 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 + ...)
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