简体   繁体   中英

C++ Pi Approximation using Leibniz Formula

I'm a beginner at C++ and coding itself, so please forgive any vocabulary mishaps. I couldn't find this specific question but similar ones on the internet, but I'm still having a hard time getting an outcome I need.

So I'm using the Leibniz Formula to approximate pi which is:

pi = 4 · [ 1 – 1/3 + 1/5 – 1/7 + 1/9 … + (–1 ^ n)/(2n + 1) ].

I've written a compilable and runnable program , but the main part of the code that's troubling me is:

if (terms > 0){

        double partial = 0;

        for (i = 0; i < terms; i++)
            if (i % 2 == 0)
                partial -= (pow(-1,terms))/((2.0 * i) + 1);
            else
                partial += (pow(-1,terms))/((2.0 * i) + 1);

        double newPi = 4 * partial;

        cout << "The approximation is " << newPi << " using " << terms << " terms.\n";

}

If terms = 3, the approximation = 2.895

If terms = 10, the approximation = 3.232

If terms = 50, the approximation = 3.161

I'm not getting any of these numbers. I've noticed though, that when I put in an odd number, I get a negative and vice versa with even numbers. Everything I have written in my program is everything I have learned in my class so far, so I cannot really go out of the scope I've written in. Any help or explanation would be appreciated.

You have an if/else to determine the sign, but then you also do pow(-1, terms) . I would just get rid of the pow and replace it with 1 , since you are already doing partial += and partial -= depending if i is odd or even. Also, I think your += and -= should be the other way around.

Try this:

if (terms > 0){
     double partial = 0;
     for (i = 0; i <= terms; i++)
         partial += pow(-1,i)/(2.0 * i + 1);
     double newPi = 4 * partial;
     cout << "The approximation is " << newPi << " using " << terms << " terms.\n";
}
if (terms > 0){
        double newPi  = 0.0;
        for (int i=0; i < n; ++i) { 
            newPi += sign / (2.0 * i + 1.0);
            sign  = -sign; 
        }
        newPi *= 4;
        cout << "The approximation is " << newPi << " using " << terms << " terms.\n";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM