![](/img/trans.png)
[英]Recursive function to reverse an array implementation of a queue in Java
[英]Recursive implementation of the Wallis function in Java
这是瓦利斯 function:
我正在努力递归地实现它。 这是我最好的尝试:
private static double computePiOver2(int n) {
int original_n = n;
double prod = 1.0;
int reps = 0;
if(reps == original_n)
return prod;
else {
reps += 1;
n += 1;
prod *= computePiOver2(2*n/(2*n-1)*(2*n/(2*n+1)));
return prod;
}
我正在使用此代码对其进行测试
public static void main(String[] args) {
for(int i = 0; i < 100; i++){
System.out.println(Math.PI/2 + " vs. " + computePiOver2(i));
}
}
但我的答案始终是 1.0。 我做错了什么?
我尝试将n
设为双倍:
private static double computePiOver2(double n) {
int original_n = (int) n;
double prod = 1.0;
int reps = 0;
if(reps == original_n)
return prod;
else {
reps += 1;
n += 1;
prod *= computePiOver2(2*n/(2*n-1)*(2*n/(2*n+1)));
return prod;
}
}
但我只是得到一个stackoverflow错误。
我有两个错误,integer 除法(感谢@azurefrog )和不正确的递归技术(感谢@David M )。 我应该像这样计算递归调用
(2n/(2n-1))*(2n/(2n+1)) * computePiOver2(n-1)
这是工作 function:
private static double computePiOver2(int n) {
double prod = 1.0;
int reps = 0;
if(reps == n)
return prod;
else {
reps += 1;
return 2.0*n/(2*n-1)*(2.0*n/(2*n+1)) * computePiOver2(n-1);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.