Search code examples
c++functionloopspitaylor-series

Calculating Pi using the Taylor series C++


I'm trying to implement a function to calculate pi using the taylor series, here is my code to do that

#include <iostream>
#include <math.h>
using namespace std;

double pi(int n)
{
double sum = 1.0;
int sign = -1;

for (int i = 1; i < n; i++)
{
    sum += sign / (2.0 * i + 1.0);
    sign = -sign;
}
return 4.0 * sum;
}


int main()
{
 cout << "the value for pi is" << pi ;
}

For some reason my code keeps returning 1, but I cant see why

as a side note I want to make it so the code doing the taylor series stops running if the absolute value of the latest term of the series is less than the error in the latest estimate for pi

I was thinking of doing this by using a similar for loop to calculate the error, and a do... while loop across the whole function that stops the calculation of pi once this condition is met, but I'm not sure if there's an easier way to do this or where to start.

I'm fairly new to this forum and c++, any help I can get is really appreciated


Solution

  • You should evaluate the function with some value, for example 10:

    cout << "the value for pi is " << pi(2000)<<endl;
    

    Output:

    the value for pi is 3.14109