Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement GROWTH function in JavaScript

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.

like image 410
Ismael Ghalimi Avatar asked Jan 04 '13 17:01

Ismael Ghalimi


People also ask

What is growing 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.

How do you use growth function in sheets?

GROWTH is a function in Google Sheets that calculates the exponential growth of a series of numbers. The syntax of the GROWTH function is as follows: =GROWTH(base, multiplier, number_of_periods) The base is the starting number in the series. The multiplier is the growth rate.


1 Answers

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.

like image 71
Ilmari Karonen Avatar answered Sep 23 '22 11:09

Ilmari Karonen