newsenpai
newsenpai

Reputation: 27

JAVA Recursive bisection method


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

I am dealing with a recursive bisection method/algorithm. I've put my recursion in the else/else if statement and don't know if I'm wrong or not. It also returns the correct root without recursion there, but the main issue is to do that with recursion.

Upvotes: 0

Views: 109

Answers (1)

newsenpai
newsenpai

Reputation: 27

Okay, I found the way out.

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

Upvotes: 0

Related Questions