I'm trying to create a formula for calculating PI using the Gregory-Leibniz series. I've created a for loop that's populating a new array with the individual values, but I need a way to then alternate between subtracting and adding each array item and then spit out the resulting number. Essentially, I need to get to something like this:
(4/1) - (4/3) + (4/5) - (4/7) + (4/9) - (4/11) + (4/13) - (4/15)
The following for loop is populating the new array correctly:
var arrLimit = 39;
var newArray = [];
for(i = 1; i <= arrLimit; i += 2) {
newArray.push(4/i);
}
At this point I get stuck. I need some way to take newArray and alternate between subtracting and adding the values, and then produce the final number.
You can sum your array with reduce, then judge *=-1 or *=1 based on the index of the array.
The code will be like below:
//Test Case 1
var arrLimit = 39;
var newArray = [];
for(i = 1; i <= arrLimit; i += 2) {
newArray.push(4/i);
}
console.log(newArray.reduce(function(pre, cur, currentIndex){
return pre+cur*(currentIndex%2 ? -1 : 1);
}, 0));
//Test Case 2
arrLimit = 11139;
newArray = [];
for(i = 1; i <= arrLimit; i += 2) {
newArray.push(4/i);
}
console.log(newArray.reduce(function(pre, cur, currentIndex){
return pre+cur*(currentIndex%2 ? -1 : 1);
}, 0));