Reputation: 37
I'm a bit new at stacks so I'm not quite sure I fully understand what the StackOverflowError entails. I did read that it mostly occurs in recursion that never ends.
public double calculateLeibniz(double pi, double x, long l) {
if (l == 10000) {
return pi;
}
if (l % 2 == 0) {
pi -= (1.0/x);
return calculateLeibniz(pi, x + 2.0, l + 1);
} else {
pi += (1.0/x);
return calculateLeibniz(pi, x + 2.0, l + 1);
}
}
I'm trying to calculate PI using the Leibniz method and figured I'd try to flex my recursion muscles. I'm not sure why it returns the error as the method is set to terminate after 10000 iterations. Is there an error in that itself where using a loop would be more efficient?
Upvotes: 3
Views: 104
Reputation: 2540
10000 is a pretty deep stack! The JVM is undoubtedly bombing out before you reach your "limit". I propose that you re-implement your method iteratively rather than recursively. Something like this...
public double calculateLeibniz(double pi, double x, int l) {
while (l < 10000) {
if (l % 2 == 0) {
pi -= 1.0/x;
} else {
pi += 1.0/x;
}
x += 2.0;
++l;
}
return pi;
}
In this case, your algorithm's stack depth is very shallow: 1 stack frame deep, to be specific.
Upvotes: 2