\$\begingroup\$
\$\endgroup\$
3
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);
200_success
146k22 gold badges190 silver badges479 bronze badges
-
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\$200_success– 200_success2022年05月11日 19:54:10 +00:00Commented 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– greybeard2022年05月12日 11:57:28 +00:00Commented May 12, 2022 at 11:57
-
\$\begingroup\$ (It may improve precision to sum starting from small terms.) \$\endgroup\$greybeard– greybeard2022年05月12日 12:04:53 +00:00Commented May 12, 2022 at 12:04
1 Answer 1
\$\begingroup\$
\$\endgroup\$
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);
}
answered May 12, 2022 at 6:32
Explore related questions
See similar questions with these tags.
default