Sunday, March 8, 2015

Least squares method in Java

Wikipedia

Calculating the coefficients:

static public double[] leastSqCoeff(double[] x, double[] y, int degree) {

    if (degree < 0) {
        throw new IllegalArgumentException();
    }
    ++degree;
    int n = x.length;
    double[][] a = new double[n][degree];
    double[] b = new double[degree];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < degree; j++) {
            a[i][j] = Math.pow(x[i], j);
        }
    }
    double[][] ata = new double[degree][degree];
    for (int i = 0; i < degree; i++) {
        for (int j = 0; j < degree; j++) {
            ata[i][j] = MatricesBasic.vectorM(MatricesBasic.getColumn(a, i), MatricesBasic.getColumn(a, j));
        }
        b[i] = MatricesBasic.vectorM(MatricesBasic.getColumn(a, i), y);
    }
    b = Matrices.gauss(ata, b);
    return b;

}

Approximating the value based on the coefficients:

static public double leastSqVal(double[] coef, double val) {

    double res = 0;
    for (int i = 0; i < coef.length; i++) {
        res += coef[i] * Math.pow(val, i);
    }
    return res;
}

This is part of the Function Approximations project.

No comments: