Thursday, March 5, 2015

Root approximation methods in Java

RootApproximations.java
This is a class containing implementations of known numerical analysis algorithms for root approximation. The error margin can be specified and has a default value of 5e-7.The function is represented with a class implementing a specific interface and must contain a method for f(x) and f'(x). Check github for examples.

Algorithms:

Root.java
A simple Java class to easily save the value and the loops required to reach root approximations.

public class Root {
    private final double value;
    private final int loops;

    public Root() {
        value = Double.NaN;
        loops = -1;
    }

    public Root(double v, int l) {
        value = v;
        loops = l;
    }

    public double getValue() {
        return value;
    }

    public int getLoops() {
        return loops;
    }
}

Secant method in Java

Wikipedia

public Root secant(double starting, double ending) {

    double x0 = starting;
    double x1 = ending;
    double xn;
    int loops = 0;
    while (true) {
        loops++;
        xn = nextSecantValue(x0, x1);
        if (Math.abs(xn - x1)  < e/* * 2*/) {
            return new Root(xn, loops);
        }
        x0 = x1;
        x1 = xn;
    }
}
private double nextSecantValue(double x0, double x1) {
    return (x1 - (function.f(x1) * ((x1 - x0) / (function.f(x1) - function.f(x0)))));
}

This is part of the RootApproximations project.

Newton-Raphson method in Java

Wikipedia

public Root newtonRaphson(double starting) {

    double x0 = starting;
    double x1;
    int loops = 0;
    while (true) {
        loops++;
        x1 = newton(x0);
        if (Math.abs(x1 - x0) < e ) {
            return new Root(x1, loops);
        }
        x0 = x1;
    }
}
private double newton(double x0) {
    return (x0 - (function.f(x0) / function.fd(x0)));
}


This is part of the RootApproximations project.

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.