![](/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.