patternjavascriptMinor
Computationally approximating PI
Viewed 0 times
computationallyapproximatingstackoverflow
Problem
Is this an efficient way to compute the value of Pi, where the limit of
The formula I used to write this is:
$$\pi \equiv \frac{4}{1}-\frac{4}{3}+\frac{4}{5}-\frac{4}{7}+\cdots$$
j \$\propto\$ accuracy?PI = 0;
for (var j = 1; j < 100; j+=2) PI += (4/j)*((j+1)%4?1:-1);The formula I used to write this is:
$$\pi \equiv \frac{4}{1}-\frac{4}{3}+\frac{4}{5}-\frac{4}{7}+\cdots$$
Solution
Your code will work eventually, but this series converges very very slowly. In fact, as you can read on Wolfram's web site:
... this sum converges so slowly that 300 terms are not sufficient to calculate pi correctly to two decimal places!
Here's a better way to do it which implements this function:
$$ \pi = \sum_{k=0}^\infty \frac{4(-1)^k}{2k+1} \bigg(\frac{1}{2^{2k+1}} + \frac{1}{3^{2k+1}}\bigg)$$
`(function(){
PI=0;
n=-4;
for(k=0;k
... this sum converges so slowly that 300 terms are not sufficient to calculate pi correctly to two decimal places!
Here's a better way to do it which implements this function:
$$ \pi = \sum_{k=0}^\infty \frac{4(-1)^k}{2k+1} \bigg(\frac{1}{2^{2k+1}} + \frac{1}{3^{2k+1}}\bigg)$$
`(function(){
PI=0;
n=-4;
for(k=0;k
Context
StackExchange Code Review Q#150902, answer score: 2
Revisions (0)
No revisions yet.