Thursday, March 5, 2015

Bisection method in Java

Wikipedia

public Root bisection(double a, double b) {

    double c;
    int loops = 0;
    while (true) {
        loops++;
        c = (a + b) / 2.0;
        if (Math.abs(b - a) <= e) {
            return new Root(c, loops);
        }
        if (hasRoot(a, c)) {
            b = c;
        }else if (hasRoot(c, b)){
            a = c;
        }
    }
}

public Root bisection(double a, double b,boolean exists) {
    double c;
    int loops = 0;
    while (true) {
        loops++;
        c = (a + b) / 2.0;
        if (Math.abs(b - a) <= e || (function.f(c)==0 && !exists)) {
            return new Root(c, loops);
        }
        if (hasRoot(a, c)) {
            b = c;
        }else if (hasRoot(c, b)){
            a = c;
        }else if(exists){
            a = c;
        }
        else
            return new Root();
    }
}

private boolean hasRoot(double a, double b) {
    return function.f(a) * function.f(b) < 0;
}


This is part of the RootApproximations project.

No comments: