I converted the pseudo-code here into C#, and have it recursively repeat 10,000 times. But I get a C# runtime error, StackOverflow Exception
after 9217
times. How can I prevent this?
EDIT If it helps anybody, here's the code:
private double CalculatePi(int maxRecursion)
{
return 2 * CalculatePi(maxRecursion, 1);
}
private double CalculatePi(int maxRecursion, int i)
{
if (i >= maxRecursion)
return 1;
return 1 + i / (2.0 * i + 1) * CalculatePi(maxRecursion, i + 1);
}
double pi = CalculatePi(10000); // 10,000 recursions
EDIT2 So everybody seems to agree that i need to convert this to iterative... can anybody give some code? I can't seem to write any iterative code that works...
EDIT Thanks to Paul Rieck for this answer, which I tested, and it works:
private static double CalculatePi(int maxRecursion)
{
double result = 1;
for (int i = maxRecursion; i >= 1; i-- )
{
result = 1 + i / (2.0 * i + 1) * result;
}
return result * 2;
}