user3397709
user3397709

Reputation: 1

C - recursive program to calculate Pi runs out of recursion stacks?

my code for the program looks like this

#include <iostream>
#include <cmath>
using namespace std;

double pi (double);

int main()
{
 cout << "Enter n to value of pi: "; double n; cin>>n;
 cout << pi(n) << endl;

 return 0;
}


double pi (double n)
{
 if (n==1)
  return 4*1;
 else
  return ( 4*(pow(-1,n+1)*(1/(2*n-1))) + pi(n-1) );
}

except it's in C (I literally only changed the include statements, scanf, printf).

The program keeps crashing if i enter 0.00001 or anyhting less for epsilon

where epsilon means (i just rearrange epsilon in that equation to find n, then use n as the paramaeter for recursion) http://puu.sh/7ot1P.png

I think it's because it's doing too much recursion. Any way to fix it?

BTW the error is segmentation fault (core dumped) when I run it on a unix server

Upvotes: 0

Views: 961

Answers (3)

halex
halex

Reputation: 16403

As you correctly suppose you are recursing too deep and therefore get a stack overflow. On my machine (Linux Mint 16 64 Bit) the maximum size of the stack is 8MB, and your code runs well up to a call of ca. pi(230000).

To solve this problem you have 3 options:

  • Increase the size of the stack with the command ulimit -s size_in_kB. That only works on Unix based systems and can lead to problems when you use a too large value for the stack size.
  • Change your approximation algorithm from an recursive to an iterative one.
  • Use an algorithm that faster converges, see https://en.wikipedia.org/wiki/Approximations_of_%CF%80 for some ideas

Upvotes: 0

  1. type of n should be int.
  2. I think n should be greater or equal to 1.
  3. the recursion function pi() need add end condition when n<1.

Upvotes: 0

Philip
Philip

Reputation: 1078

pi() expects a double, you give int.

Upvotes: 2

Related Questions