Home > Blockchain >  Approximation of Pi using Liebniz Formula in C
Approximation of Pi using Liebniz Formula in C

Time:10-21

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;

CodePudding user response:

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;

CodePudding user response:

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;
}
  •  Tags:  
  • c
  • Related