我尝试使用以下方法计算 PI:(Java 代码)
private static double calculate(double k) {
return (
( 3 * Math.pow(2, k-1) ) *
Math.sqrt(
2 - (2 * Math.sqrt(
1-(
Math.pow((calculate(k-1) / ( 3*Math.pow(2, k-1) )), 2)
)
))
)
);
}
我在线程“主”java.lang.StackOverflowError 中遇到异常,在我尝试递归调用方法本身的那一行。
有什么想法或建议吗?
最佳答案
您可以使用尾递归(动态规划)而不是简单递归来计算它,如下所示:
private static double calculate(double k) {
double result = 3 * Math.sqrt(2);
for(int i = 2; i <= k; i++)
result = 3*Math.pow(2, k-1)*Math.sqrt(2-(2*Math.sqrt(1-Math.pow(result / ( 3*Math.pow(2, k-1) ), 2)));
return result;
}
在这种方法中,您无需担心 stackoverflow。此外,在递归实现中,您在实现和运行时间方面具有良好的性能。
关于java - 递归计算PI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47365721/