Skip to content

Instantly share code, notes, and snippets.

@kdubbels
Created January 16, 2021 05:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kdubbels/bf8d1915c987382e9924489042eb1aef to your computer and use it in GitHub Desktop.
Save kdubbels/bf8d1915c987382e9924489042eb1aef to your computer and use it in GitHub Desktop.
Calculate digits of pi using Leibniz's formula
// https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80
//
// Requires lodash or underscore for the `range` function
function calculatePi(nTerms) {
var numerator = 4;
var denominator = 1;
var operation = 1;
var pi = 0;
const range = _.range(nTerms);
for (let i = 0; i < range.length; i++) {
pi += operation * (numerator / denominator);
denominator += 2;
operation *= -1;
}
return pi;
}
calculatePi(100000000) // 3.141592643589326 (The actual value is 3.1415926535897. It will get more accurate with a larger input)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment