Created
December 10, 2014 14:39
-
-
Save bellbind/f61c02383c501af6efde to your computer and use it in GitHub Desktop.
[javascript]Calculating 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
// calculating PI | |
console.log(Math.PI); | |
var pi1 = function (n) { | |
// Bailey-Borwein-Plouffe | |
var r = 0; | |
for (var i = 0; i < n; i++) { | |
var b = 8 * i; | |
r += (4/(b+1) - 2/(b+4) - 1/(b+5) - 1/(b+6)) / Math.pow(16, i); | |
} | |
return r; | |
}; | |
console.log(pi1(11)); // === Math.PI | |
var pi2 = function (n) { | |
// Adamchik-Wagon | |
var r = 0; | |
for (var i = 0; i < n; i++) { | |
var b = 4 * i; | |
r += (2/(b+1) + 2/(b+2) + 1/(b+3)) / Math.pow(-4, i); | |
} | |
return r; | |
}; | |
console.log(pi2(24)); // pi2(24) === pi2(25) | |
var pi0 = function (n) { | |
// Leibniz | |
var r = 0; | |
for (var i = 0; i < n; i++) { | |
r += (i % 2 === 0 ? 1 : -1) / (2 * i + 1); | |
} | |
return 4 * r; | |
}; | |
console.log(pi0(10000000)); // until 7-digits | |
//console.log(pi0(1000000000)); // until 9-digits |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
result