Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating Pi in JavaScript using Gregory-Leibniz Series

Tags:

javascript

pi

I have to calculate value of Pi using Gregory-Leibniz series:

pi = 4 * ((1/1 - 1/3) + (1/5 - 1/7) + (1/9 - 1/11) + ...)

I want to write a function in JavaScript that would take the number of digits that needs to be displayed as an argument. But I'm not sure if my way of thinking is fine here.

This is what I got so far:

function pi(n) {
  var pi = 0;
  for (i=1; i <= n; i+2) {
    pi = 4 * ((1/i) + (1/(i+2)))
  }
  return pi;
}

How do I write the pi calculation so it calculates values till n?

like image 539
Joanna Avatar asked Sep 19 '16 13:09

Joanna


People also ask

How is Leibniz pi calculated?

The Leibniz formula for π4 can be obtained by putting x = 1 into this series. It also is the Dirichlet L-series of the non-principal Dirichlet character of modulus 4 evaluated at s = 1, and therefore the value β(1) of the Dirichlet beta function.

How do you calculate pi in JavaScript?

To get the value of PI in JavaScript, use the Math. PI property. It returns the ratio of the circumference of a circle to its diameter, which is approximately 3.14159.

How do you find the pi of a series?

Once you've got the circumference and diameter, plug them into the formula π=c/d, where "π" is pi, "c" is circumference, and "d" is diameter. Just divide the circumference by the diameter to calculate pi!


Video Answer


1 Answers

You could use an increment of 4 and multiply at the end of the function with 4.

n is not the number of digits, but the counter of the value of the series.

function pi(n) {
    var v = 0;
    for (i = 1; i <= n; i += 4) {  // increment by 4
        v +=  1 / i - 1 / (i + 2); // add the value of the series
    }
    return 4 * v;                  // apply the factor at last
}

console.log(pi(1000000000));
like image 198
Nina Scholz Avatar answered Oct 22 '22 09:10

Nina Scholz