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


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

pi in your example is a function that takes an argument. Hence you have to add parenthesis and an argument like this pi(50) . 50 is just an example use whatever you want.

链接地址: http://www.djcxy.com/p/70990.html

上一篇: HTML复选框可以设置为只读吗?

下一篇: 使用泰勒级数C ++计算Pi