So I wanted to do something different so I tried to create a program to calculte Pi. I am still new to programming so forgive me for my atrocity of a program.
import java.math.BigDecimal; import java.math.RoundingMode; public class pi { public static BigDecimal pie = new BigDecimal(4); public static void pi(int count, int a, int stop){ BigDecimal count1 = new BigDecimal(count); BigDecimal a1 = new BigDecimal(a); pie= pie.add(new BigDecimal(4).divide(a1.multiply(count1), 20, BigDecimal.ROUND_HALF_UP)); System.out.println(pie); if (stop<1000000) pi(count*-1, a+2, stop+1); } public static void main(String[] args) { // TODO Auto-generated method stub pi(-1,3,0); } } Result:
2.66666666666666666667
3.46666666666666666667
2.89523809523809523810
3.33968253968253968254
...
...
3.14137796917835535721
3.14180729192172768736
3.14137806131758561203
3.14180719982203792401
and then I got a stack overflow exception.
My question is what is wrong with my program, as I checked 4 of the first recursions give the right result but the program can't still get to pi as more recursions happen.
Edit: thanks for all of the comments and answers. Now that I know better, I will use better series and write the program iteratively. I've read about the downsides of recursions before but didn't see it for myself until now.
Another question I have now is does recursion have a limit in the number of loops? Because in this situation it apparently does.