如何在JavaScript中实现GROWTH函数

时间:2013-01-04 17:34:39

标签: javascript excel excel-formula

我正在尝试在JavaScript中实现Microsoft Excel的GROWTH功能。此函数使用现有数据计算预测的指数增长。令它变得棘手的是它必须使用多组known_x's值。我找不到任何参考方程式。有什么建议吗?

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

以下是基于my answer at math.SE和维基百科页面中的simple linear regression公式的重新实现:

function growth ( known_y, known_x, new_x, use_const ) {
    // default values for optional parameters:
    if ( typeof( known_x ) == 'undefined' ) {
        known_x = [];
        for ( var i = 1; i <= known_y.length; i++ ) known_x.push(i);
    }
    if ( typeof( new_x ) == 'undefined' ) {
        new_x = [];
        for ( var i = 1; i <= known_y.length; i++ ) new_x.push(i);
    }
    if ( typeof( use_const ) == 'undefined' ) use_const = true;

    // calculate sums over the data:
    var n = known_y.length;
    var avg_x = 0; var avg_y = 0; var avg_xy = 0; var avg_xx = 0; 
    for ( var i = 0; i < n; i++ ) {
        var x = known_x[i]; var y = Math.log( known_y[i] );
        avg_x += x; avg_y += y; avg_xy += x*y; avg_xx += x*x;
    }
    avg_x /= n; avg_y /= n; avg_xy /= n; avg_xx /= n;

    // compute linear regression coefficients:
    if ( use_const ) {
        var beta = (avg_xy - avg_x*avg_y) / (avg_xx - avg_x*avg_x);
        var alpha = avg_y - beta*avg_x;
    } else {
        var beta = avg_xy / avg_xx;
        var alpha = 0;
    }
    // console.log("alpha = " + alpha + ", beta = " +  beta);

    // compute and return result array:
    var new_y = [];
    for ( var i = 0; i < new_x.length; i++ ) {
        new_y.push( Math.exp( alpha + beta * new_x[i] ) );
    }
    return new_y;
}

Here's a demo on ideone.com.您可以将输出与Excel GROWTH documentation page上的演示工作表进行比较。

请注意,算法中求和循环的数值稳定性可以使用诸如calculating the variance的维基百科页面上描述的技术来改进,如Kahan summation。但是,对于像这样的简单例子,天真求和循环非常好。