The value of π can be determined by the series equation
π =4 * ( 1 −1/3+1/5 −1/ 7+1 /9− 1/ 11+1/13+... )
Write a recursive function that takes an odd number n and uses recursion to
approximate the value of π using the given formula including term up through 1/n.
Your function prototype must be as follows:
float PiValue(int n);
Calling this function “PiValue(1875)” should give the answer 3.14052655581

i am really stuck in this program . Can anyone help me?

#include<cmath>
#include<iostream>
using namespace std;
float pic(int n)
{

float pi=4*(pow(1,n)*(1/(2*n-1)));

if(n==1)
{
    return pi;
}

    else
    {

    return pi+pic(n-1);
}
}
int main()
{
    int num;
   cout<<"Enter the odd number  "<<endl;    
   cin>>num;
   int r=pic(num);
   cout<<r<<endl;


   return 0;
}

Recommended Answers

I have thoughts about this one.

  1. Since it's float, just declare the value and be done.
  2. Use the old pi = 4.0 * atan(1.0)
  3. See more than 74 other solutions at …
Jump to Post

All 2 Replies

If you are going to calculate pi as the sum of a series then you should sum from the smallest term to the largest to avoid losing small values due to the limitations of your storage type. While this will not matter if you are using a small number of terms (adding 1/5 to your sum will not result in the loss of accuracy) but in calculating with a large number of terms it will. When you are doing your recursion you will start with your limit and decrease by 2 each call, stopping at 1.

Of course, due to the overhead in stack maiintenance, you would not normally use a recursive solution for this type of problem (factorial for another) other than as an exercise for learning recursion. In python, the largest limit I can use before getting a RecursionError is 1987, and that only gets me to 3.140586617627045 as an approximation to pi.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.