Reputation: 1
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
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:
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.Upvotes: 0
Reputation: 95
Upvotes: 0