Skip to content

Instantly share code, notes, and snippets.

@Airbus-A330
Created April 23, 2023 04:38
Show Gist options
  • Save Airbus-A330/a2570af85659001ae605502cd9ee0e1b to your computer and use it in GitHub Desktop.
Save Airbus-A330/a2570af85659001ae605502cd9ee0e1b to your computer and use it in GitHub Desktop.
Taylor Series Approximation for Pi
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)}%
`);
})();
@Airbus-A330
Copy link
Author

Airbus-A330 commented Apr 23, 2023

Not the most efficient, but gets the job done.

The script essentially uses the Maclaurin arctan series where x is 1 and n is the defined number in the pi() function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment