0

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.

  • 4
    Did you mean to use `j` instead of `iteration` in `sum += sign * 4.0 / ((2 * j) * (2 * j + 1.0) * (2 * j + 2.0))`? – mvp Apr 03 '19 at 19:12
  • You should define `iteration` as integer since you declared it as such. A minor correction: `int iteration = 0;` – Ely Apr 03 '19 at 19:25
  • Unrelated: [Do not `#include`](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h). – user4581301 Apr 03 '19 at 19:27

2 Answers2

2

The line:

sum = sum + sign * 4.0 / ((2 * iteration) * (2 * iteration + 1.0) * (2 * iteration + 2.0));

never changes with different iterations, you're just subtracting and adding the same thing back and forth. you need to replace iteration with j

sum = sum + sign * 4.0 / ((2 * j) * (2 * j+ 1.0) * (2 * j+ 2.0));
Hoog
  • 2,215
  • 1
  • 12
  • 19
0

for (int j = 1; j < iteration; j++) loop is never executed for a starting value of iteration = 0.0

Tetix
  • 289
  • 2
  • 10
  • 3
    `iteration` is overwritten by console input here: 'std::cin >> iteration' before the loop starts – Hoog Apr 03 '19 at 19:13