Joanna - 1 year ago 190

Javascript Question

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 number of digits that needs to be displayed as an argument. But I'm not sure if my way of thinking is fine here, I have just started learning JS.

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 pi calculation so it calculates values till

`n`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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));
```