C++ Pi Approximation using Leibniz Formula

安稳与你 提交于 2019-12-11 06:58:08

问题


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.


回答1:


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.




回答2:


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";
}


来源:https://stackoverflow.com/questions/39987538/c-pi-approximation-using-leibniz-formula

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!