Question

I'm just learning C++ and so I have started to make a simple program to approximate the value of pi, using the series: Pi ^ 6 / 960 = 1 + 1 / 3 ^ 6 + 1 / 5 ^ 6... and so on continuing with denominators of odd numbers to the power of 6. Here is my code:

/*-------------------------------------------
 *  AUTHOR:                                 *
 *  PROGRAM NAME: Pi Calculator             *
 *  PROGRAM FUNCTION: Uses an iterative     *
 *      process to calculate pi to 16       *
 *      decimal places                      *
 *------------------------------------------*/
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
double pi_approximation = 0; // the approximated value of pi
double iteration = 3; // number used that increases to increase accuracy
double sum = 1; // the cumulative temporary total

int main ()
{
    while (true) // endlessly loops
    {
        sum = sum + pow(iteration,-6); // does the next step in the series
        iteration = iteration + 2; // increments iteration
        pi_approximation = pow((sum * 960),(1 / 6)); // solves the equation for pi
        cout << setprecision (20) << pi_approximation << "\n"; // prints pi to maximum precision permitted with a double
    }
}

The code seems to work fine (both the variables 'sum' and 'iteration' increase correctly) up to this line here:

pi_approximation = pow((sum * 960),(1 / 6)); // solves the equation for pi

as for some reason 'pi_approximation' retains its value of 1 and as such the text printed to 'cout' is "1".

Was it helpful?

Solution

The problem is integer division:

(1 / 6) will return 0. As I am sure you know, anything to the power of 0 is 1.

For floating point division, change to ((double)1 / (double)6) or (1.0 / 6.0).

OTHER TIPS

(1 / 6) == 0 because it is using integer math - you probably want (1.0 / 6.0)...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top