首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JAVA递归二分法

JAVA递归二分法
EN

Stack Overflow用户
提问于 2022-10-23 15:07:53
回答 1查看 37关注 0票数 0
代码语言:javascript
复制
    private double EPSILON = 0.25;
    private int iteration = 0;

    public double f(double x){
        return x*x - 2;
    }

    public double bisection(double a, double b){ //main algorithm

        iteration++;

        if(f(a) * f(b) >= 0){
            return 0.0; // Wrong [a, b]
        }

        double c = a;
        while((b-a) >= EPSILON){

            c = (a+b)/2; // middle point

            if(f(c) == 0.0){ // that means middle point is the root
                break;
            }
            else if (f(c)*f(a) < 0){
                b = c;
                bisection(a, b); // continue calculating by recu
            }
            else{
                a = c;
                bisection(a, b);
            }
        }
        return c;
    }

    public int getIteration(){
        return iteration;
    }
}

我正在处理一种递归二分法/算法。我把递归放在了or /else if语句中,不知道我是否错了。它也返回不需要递归的正确的根,但是主要的问题是使用递归。

EN

回答 1

Stack Overflow用户

发布于 2022-10-23 15:41:29

好吧,我找到出路了。

代码语言:javascript
复制
    private double EPSILON = 0.25;
    private int iteration = 0;
    private double c = 1.0;

    public double f(double x){
        return x*x - 2;
    }

    public double bisection(double a, double b){ //main algorithm

        iteration++;

        if(f(a) * f(b) >= 0){
            return 0.0; // Wrong [a, b]
        }

        if((b-a) >= EPSILON){

            c = (a+b)/2; // middle point

            if(f(c) == 0.0){ // that means middle point is the root
                return c;
            }
            else if (f(c)*f(a) < 0){
                b = c;
                bisection(a, b);
            }
            else {
                a = c;
                bisection(a, b);
            }
        }
        return c;
    }

    public int getIteration(){
        return iteration;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74172214

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档