I tried to write a program in C++ that can calculate pi using the Nilakantha Series. I looked at other programs, but they seemed to use the same methods, that did not work with my program. I also tried it using the Gregory-Leibniz Series, but that led to a similar problem. The sum converges to 3 instead of pi. Have I implemented the Series wrong or is there a problem with the program in general?
#include <iostream>
#include <math.h>
#include<bits/stdc++.h>
//variables
float sign = -1.0;
float sum = 0.0;
float start = 3.0;
int iteration = 0.0;
int main() {
std::cout << "How many iterations should be completed?" << std::endl;
std::cin >> iteration;
//code for calculating pi
for (int j = 1; j < iteration; j++) {
sum = sum + sign * 4.0 / ((2 * iteration) * (2 * iteration + 1.0) * (2 * iteration + 2.0));
sign *= -1.0;
}
// output
std::cout << std::fixed << std::setprecision(100) << sum + start << std::endl;
return 0;
}
So the Output is 3 for a relatively high amount of iterations, but it should converge to pi.