snippet: LinearLeastSquares para javascript

Por esas cosas de la vida un amigo necesitaba un interpolador simple para javascript; asi que hice este de minimos cuadrados.

Uso:

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

El Código

/**
 * Creates an interpolator function with "Linear Least Square" method.
 *
 * @see http://en.wikipedia.org/wiki/Linear_least_squares_(mathematics)
 * @params xs: array with x's values (same lenght as ys)
 * @params xs: array with y's values (same lenght as xs)
 *
 * @author Juan BC
 * @licence gpl3
 * @date 2011/01/05
 *
 */
function LinearLeastSquares(xs, ys){

    //Constructor
    if (xs.length != ys.length){
        throw "'xs' and 'ys' must have same lenght";
    }

    var n = xs.length;
    var sum_xy = 0;
    var sum_x = 0;
    var sum_y = 0;
    var sum_x_sq = 0;
    for(var 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;
    //Constructor

     /**
     * Return the interpolation of x
     * @param x
     */
    this.interpolate = function(x){
        return this._b + this._m * x;
    }
    
}

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

Leer Más