Estimation of PI using the Liebniz formula.

+1 Hans Magnus Dahlen · November 22, 2015
Hi Guys.
I have written some code that is supposed to estimate the value of PI using the Liebniz formula.
https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80

When I COUT the result it just says 1.

This might be a stupid question, but what am I doing wrong here?
Here is the code:


int leibnizPi(int n)
{
    double pi=0;


    for (x=1; x<=n; x++)
    {
        if (x%2 == 0)
        {
            pi = pi - (1 / ((2*x)-1));                                      
        }



        else
        {
             pi = pi + (1 / ((2*x)-1));                                    
        }

   }

    cout <<setprecision(50);
    cout <<fixed;

    cout <<pi*4<<endl;

    return 0;
}

Post a Reply

Replies

Oldest  Newest  Rating
0 Hans Magnus Dahlen · November 23, 2015
Correction: It outputs 4, not 1 :-) 
0 Hans Magnus Dahlen · November 24, 2015
1/19
0 Hans Magnus Dahlen · November 24, 2015
Problem solved.
It was an integer division error.
x was declared as int.
  • 1

C++

107,195 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator