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
The recursive call is not tail-recursive, and even if it were, it wouldn't help since the C# compiler does not currently optimize tail-recursive calls. EDIT: As pointed out by Eric Lippert and Gabe, the CLR could choose to generate tail calls even when explicit tail-call instructions are not in the emitted IL.
Please don't do this. For fun only:
static void Main()
{
Console.WriteLine(SafeCalculatePi(10000));
}
// Calculates PI on a separate thread with enough stack-space
// to complete the computation
public static double SafeCalculatePi(int maxRecursion)
{
// We 'know' that you can reach a depth of 9217 for a 1MB stack.
// This lets us calculate the required stack-size, with a safety factor
double requiredStackSize = (maxRecursion / 9217D) * 1.5 * 1024 * 1024 ;
double pi = 0;
ThreadStart ts = delegate { pi = CalculatePi(maxRecursion); };
Thread t = new Thread(ts, (int)requiredStackSize);
t.Start();
t.Join();
return pi;
}