0

First of all, I'm new to coding and C++. I did my researches for my problem on the internet but the solutions are not quite worked out for me.

I'm trying to get approximation of Pi with Liebniz formula which is: Pi/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9...

The code is compilable and runnable. The problem is I get 4 as answer for every number of iterations (n value). Here is the main part of the code.

int main() {

int i ;
double a=1  ;
double pi4 = 0 ; 
long n;
cout << "Number of iterations? ";
cin >> n;

for (i=1; i <= (n) ; i += 2) {

    pi4 = pi4 + a * (1 / i);
    a = -a;

}

cout.precision(20);
cout << "Pi = " << (pi4 * 4) << endl;
return 0;
Tranistor
  • 1
  • 1
  • This isn't a very efficient way to approximate PI. Fine for an exercise, but you need at least 10000 iterations just to get PI to 2 decimal points. If you don't have a constant (line `M_PI`), then `4. * atan(1.)` is a much simpler and accurate estimation. – David C. Rankin Oct 20 '21 at 19:52

2 Answers2

0

In c++ dividing by an int is this in other languages: floor(a / int). Convert "i" to a double, or "tell" the compiler, this is a floating-point division. (Because this is an integer dividing, or Euclidean division [https://en.wikipedia.org/wiki/Euclidean_division] [https://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division])

#include <iostream>

using namespace std;

int main() {

int i ;
double a=1  ;
double pi4 = 0 ; 
long n;
cout << "Number of iterations? ";
cin >> n;

for (i=1; i <= (n) ; i += 2) {

    pi4 = pi4 + a / i;
    // pi4 = pi4 + a * (1.0 / i);
    a = -a;

}

cout.precision(20);
cout << "Pi = " << (pi4 * 4) << endl;
return 0;
}
H1N1virus
  • 51
  • 5
  • 1
    I would recommend sticking with `i` as an integer, since it's a loop variable and the comparison to `n` can get sticky if floating-point gets involved. Instead, just replace `a*(1 / i)` with `a*(1.0 / i)` or, as 1201ProgramAlarm suggested, just `a/i`. – jjramsey Oct 20 '21 at 18:08
  • 1
    @jjramsey thanks for the correction! – H1N1virus Oct 20 '21 at 19:03
0

Integer math. 1 / i will be 0 for all but the first iteration.

You can remove the reciprocal and just use a / i.

pi4 += a / i;
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56