1
\$\begingroup\$

I have created an algorithm which calculates the value of PI in JavaScript.

Can this algorithm to be improved?

let PI = 0;
for(let i=0; i<80; i++){
  let numerator = Math.pow(factorial(i), 2) *  Math.pow(2, i+1);
  let denominator = factorial((2 * i + 1));
  PI += numerator / denominator;
}

function factorial(n){
    return(n<2)?1:factorial(n-1)*n;
}

console.log("Value of pi: " + PI);
\$\endgroup\$
3
  • 7
    \$\begingroup\$ We can review your code for improvements. However, if you want to store the digits to an array but you don't already have code that does that, then that part of the question is not a code review and should be removed from the question. \$\endgroup\$ May 11, 2022 at 19:54
  • 1
    \$\begingroup\$ (It's easier to know some error limit has been "sous"passed for good with alternating series: The (Gregory-)Leibniz series looks promising.) \$\endgroup\$
    – greybeard
    May 12, 2022 at 11:57
  • \$\begingroup\$ (It may improve precision to sum starting from small terms.) \$\endgroup\$
    – greybeard
    May 12, 2022 at 12:04

1 Answer 1

1
\$\begingroup\$

There's no need to recalculate the factorials and powers from scratch each time around the loop. Remember the last values and just multiply to get the next value.

Approximate idea (untested, and by a Javascript novice, so likely containing some mistakes):

let PI = 0;
let top = 1;
let pow2 = 2;
let denominator = 1;
for (let i = 1;  i <= 80;  i++) {
  PI += top * top * pow2 / denominator;
  top *= i;
  pow2 *= 2;
  denominator *= (2 * i) * (2 * i + 1);
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.