Snippet: LinearLeastSquares pero para java

Y me dio ganas de hacerlo para java

Uso:

double[] xs = {1, 2, 3, 4, 5};
double[] ys = {1, 4, 9, 16, 25};
interpolador = new LinearLeastSquares(xs, ys);
interpolador.interpolate(1);

El Código

public class LinearLeastSquare {

    private double m;
    private double b;

    /**
     * Creates an interpolator function with "Linear Least Square" method.
     *
     * @see http://en.wikipedia.org/wiki/Linear_least_squares_(mathematics)
     * @param xs: array with x's values (same lenght as ys)
     * @param xs: array with y's values (same lenght as xs)
     *
     * @author Juan BC
     * @licence gpl3
     * @date 2011/01/05
     *
     */
    public LinearLeastSquare(double[] xs, double[] ys) {
        if (xs.length != ys.length) {
            throw new IndexOutOfBoundsException("'xs' and 'ys' must have same lenght");
        }
        double n = xs.length;
        double sum_xy = 0;
        double sum_x = 0;
        double sum_y = 0;
        double sum_x_sq = 0;
        for (int i = 0; i < xs.length; i++) {
            sum_xy += xs[i] * ys[i];
            sum_x += xs[i];
            sum_y += ys[i];
            sum_x_sq += xs[i] * xs[i];
        }

        this.m = (n * sum_xy - sum_x * sum_y) / (n * sum_x_sq - sum_x * sum_x);
        this.b = (sum_y - this.m * sum_x) / n;
    }

    /**
     * Return the interpolation of x
     * @param x
     */
    public double interpolate(double x) {
        return this.b + this.m * x;
    }
}

Disclaimer: Solo lo probé con el conjunto de datos que hay en Wikipedia.

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos necesarios están marcados *

Puedes usar las siguientes etiquetas y atributos HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>