I am learning JavaScript and decided to translate my Python scripts into JavaScript.
Approximations of π are extremely popular programming challenges and I am sure they must be a staple of the challenges one must overcome to learn a programming language.
I am sure you must be bored of this kind of questions but I have tested many algorithms and selected the algorithms that converge the fastest:
> console.log(pi(50))
3.1415926535897922
undefined
> console.log(BBP(11))
3.141592653589793
undefined
> console.log(Ramanujan(3))
3.141592653589793
undefined
>
The first function takes 50 iterations to generate the closest value before precision loss, the second function takes only 11 iterations to get the closest approximation of π possible within the IEEE-754 Binary64 (double) format, whereas the last function only takes THREE iterations!
Code
function pi (t) {
function db (x) {
if (x <= 0) { return 1 }
return x * db(x - 2)
}
let term = (x) => db(2 * x) / db(2 * x + 1) * 0.5 ** x
const stack = []
for (let i=0; i<t; i++) { stack.push(term(i)) }
return 2 * stack.reduce((s, n) => s + n, 0)
}
function BBP (t) {
const stack = []
for (let k=0; k<t; k++) {
let a = 1/16**k
let b = 4/(8*k+1)
let c = 2/(8*k+4)
let d = 1/(8*k+5)
let e = 1/(8*k+6)
let item = a * (b - c - d - e)
stack.push(item)
}
return stack.reduce((s, n) => s + n, 0)
}
function Ramanujan (t) {
function factorial (n) {
var f = 1
for (let i=1; i<=n; i++) { f *= i }
return f
}
let term = (k) => (factorial(4*k) * (1103 + 26390*k)) / (factorial(k)**4 * 396**(4*k))
const stack = []
for (let i=0; i<t; i++) { stack.push(term(i)) }
var sum = stack.reduce((a, b) => a + b, 0)
return 1 / (2 * 2**.5 * sum/9801)
}
console.log(pi(50))
console.log(BBP(11))
console.log(Ramanujan(3))
How can they be improved? (I wrote them all within half an hour.)
53*Math.log10(2)
) digits? \$\endgroup\$