Created
January 16, 2021 05:14
-
-
Save kdubbels/bf8d1915c987382e9924489042eb1aef to your computer and use it in GitHub Desktop.
Calculate digits of pi using Leibniz's formula
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
// 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