Search code examples
c++runtime-errorinfinite-looppi

Calculating Pi with C++; Where am I messing up?


for fun I am trying to calculate pi using the well-known algorithm that: pi/4 = 1 - (1/3) + (1/5) - (1/7) + (1/9), etc.... Then multiplying the resultant by 4 to get pi (approximately). I've spent the last 45 minutes or so writing and trying to get this code to work. Where am I messing up? Any help would be GREATLY appreciated.

//I'm new, which of these are necessary in this program?
#include <iostream>
using namespace std;
#include <string>
#include <math.h>

int main()
{
//1.0 as 1/4 pi is used as part of the algorithm in the for loop
float pi_fourth = 1.0;
//to be used as a counter inside for loop
int i = 5;
//I want the for loop to stop after only a few iterations
for (pi_fourth = 1.000000; i < 20 ; i + 4)
{
    //algorithm for determining one-fourth pi
    // algorithm is pi/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9, etc...
    (pi_fourth -= 1/i) += (1/(i-2));
}
//now to complete the program, I need to multiply result
//  of the for loop to get pi approx.
float real_pi = (pi_fourth * 4);
//final print statement to reveal pi to a few digits
cout << "pi is ABOUT " << endl << real_pi << endl;
return 0;
}

When it runs, no errors come out, it just never gets to the final print statement, which leads me to believe this is an infinite loop. Is that a correct assumption? I apologize if the answer is extremely simple; as I mentioned before, I'm new to C++.


Solution

  • I made a fixed version of the program with comments:

    #include <iostream>
    // Only iostream is needed for cout and endl.
    // using namespace std is usually not recommended on global scope
    
    int main()
    {
        float pi_fourth = 1.0;
        int i = 3;
        for(; i < 1000; i += 4)
        {
            // pi_fourth was already initialized. using 1.00000 instead of 1.0 has no effect.
            // i += 4 to add to i
            // fixed the algorithm, and wrote it in two statements.
            // 1.0/i instead of 1/i, otherwise it would be an integer division (because both 1 and i are integers).
            pi_fourth -= 1.0/i;
            pi_fourth += 1.0/(i + 2);
        }
        float real_pi = pi_fourth * 4.0;
        std::cout << "pi is ABOUT " << std::endl << real_pi << std::endl;
        return 0;
    }