How to implement GROWTH function in JavaScript

excel, excel-formula, javascript

Solution

Here's a reimplementation based on my answer at math.SE and the simple linear regression formulas from the Wikipedia page:

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. You can compare the output with the demo worksheet on the Excel `GROWTH` documentation page.

Note that the numerical stability of the summation loop in the algorithm could be improved using techniques such as those described on the Wikipedia page for calculating the variance, like Kahan summation. However, for simple examples like this, the naive summation loop is quite good enough.

Problem

I am trying to implement Microsoft Excel's GROWTH function in JavaScript. This function calculates predicted exponential growth by using existing data. What makes it tricky is that it must work with multiple sets of `known_x's` values. I could not find any reference equation. Any suggestions? Thanks in advance for your help.

Original source