作为一个学校项目,我试图使用泰勒扩展arctan(x)来计算pi的值,如arctan(1) = π/4。我做了这个程序计算圆周率的值,但我需要算的非常大的值来计算的话,每当我把限制超过价值,说我得到的错误:为什么在使用泰勒级数展开的pi计算中给出java.lang.StackOverflowError?
Exception in thread "main" java.lang.StackOverflowError
at extended_essay.Talyor_pi_arctan.calculate(Talyor_pi_arctan.java:18)
The line "at extended_essay.Talyor_pi_arctan.calculate(Talyor_pi_arctan.java:18)"
重复多次。
我不想处理异常,因为这会增加所需的时间。 请告诉我为什么会发生这种情况,我还可以使用其他可能的解决方案?
附加信息:
the taylor expansion of arctan(x) is
Summation of (((-1)^n)/2n+1) * ((x)^(2n+1))
我写的代码如下:calculate()事业的StackOverflowError的
public class Talyor_pi_arctan {
static double count = 0, val = 0, pi = 0, limit = 10000;
public static void main(String args[]){
calculate();
pi *= 4;
System.out.println("Value of pi calculated: " +pi);
System.out.println("Actual value of pi : " +Math.PI);
}
public static void calculate(){
if(count >= limit){
return;
}
val = (Math.pow(-1d, count)/((2 * count) + 1)) * Math.pow(1, ((2*count)+1));
pi = pi + val;
++count;
calculate();
}
}
+7
不必要的递归生产许多栈帧,导致堆栈溢出,只是把它变成一个循环 –
+0
有在你的代码中递归,它可能会导致stackoverflow例外 –
+1
请注意,这个近似值的误差是'1 /(2n + 1)'与'n'项的总和。查找“Machin-like公式”,以便更快地收敛arcus切线公式的组合。 –