简体   繁体   English

在 Java 中的 Wallis function 的递归实现

[英]Recursive implementation of the Wallis function in Java

This is the Wallis function:这是瓦利斯 function:

在此处输入图像描述

I'm struggling to implement it recursively.我正在努力递归地实现它。 This is my best attempt:这是我最好的尝试:

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;
    }

I'm testing it using this code我正在使用此代码对其进行测试

public static void main(String[] args) {
    for(int i = 0; i < 100; i++){
       System.out.println(Math.PI/2 + " vs. " + computePiOver2(i));
    }
}

But my answer is always 1.0.但我的答案始终是 1.0。 What am I doing incorrectly?我做错了什么?

I tried making n a double:我尝试将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;
        }
    }

But I just get a stackoverflow error.但我只是得到一个stackoverflow错误。

I had two errors, integer division (thanks @azurefrog ) and incorrect recursion technique (thanks @David M ).我有两个错误,integer 除法(感谢@azurefrog )和不正确的递归技术(感谢@David M )。 I was supposed to compute the recursive call like this我应该像这样计算递归调用

(2n/(2n-1))*(2n/(2n+1)) * computePiOver2(n-1)

Here is the working function:这是工作 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM