Created
April 23, 2023 04:38
-
-
Save Airbus-A330/a2570af85659001ae605502cd9ee0e1b to your computer and use it in GitHub Desktop.
Taylor Series Approximation for Pi
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
const pi = (iterations=10_000_000) => { | |
let π = 0.0; | |
for (let i = 0; i < iterations; i++) { | |
let numerator = parseFloat(Math.pow(-1, i + 1)); | |
let denominator = parseFloat(((2 * i) + 1)); | |
π += parseFloat(numerator / denominator); | |
} | |
return { | |
output: Math.abs(parseFloat(π * 4.0)), | |
degrees: iterations * 2 | |
} | |
} | |
(() => { | |
let benchmark1 = Date.now(); | |
let calculatedPi = pi(1_000_000_000); // number of approximations made | |
let benchmark2 = Date.now(); | |
console.log(`Maclaurin Series for π (${calculatedPi.toString().length.toLocaleString()} digits): | |
• Stored Pi: ${Math.PI} | |
• Calculated Pi: ${calculatedPi.output} | |
------ | |
• Degrees: ${calculatedPi.degrees.toLocaleString()} | |
• Approximation: ${(calculatedPi.degrees / 2).toLocaleString()} points | |
• Benchmark: ${(benchmark2 - benchmark1)} ms | |
• Accuracy: ${((1 - parseFloat(Math.PI - calculatedPi.output)) * 100)}% | |
`); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not the most efficient, but gets the job done.
The script essentially uses the Maclaurin arctan series where
x
is 1 andn
is the defined number in thepi()
function.