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;
}
// demo data from http://office.microsoft.com/en-us/excel-help/growth-function-HA102753003.aspx
var known_y = [33100, 47300, 69000, 102000, 150000, 220000];
var known_x = [11, 12, 13, 14, 15, 16];
var new_x = [11, 12, 13, 14, 15, 16, 17, 18, 19];
var new_y = growth( known_y, known_x, new_x );
for ( var i = 0; i < new_x.length; i++ ) {
print( new_x[i] + ": " + new_y[i] );
}
ZnVuY3Rpb24gZ3Jvd3RoICgga25vd25feSwga25vd25feCwgbmV3X3gsIHVzZV9jb25zdCApIHsKICAgIC8vIGRlZmF1bHQgdmFsdWVzIGZvciBvcHRpb25hbCBwYXJhbWV0ZXJzOgogICAgaWYgKCB0eXBlb2YoIGtub3duX3ggKSA9PSAndW5kZWZpbmVkJyApIHsKICAgICAgICBrbm93bl94ID0gW107CiAgICAgICAgZm9yICggdmFyIGkgPSAxOyBpIDw9IGtub3duX3kubGVuZ3RoOyBpKysgKSBrbm93bl94LnB1c2goaSk7CiAgICB9CiAgICBpZiAoIHR5cGVvZiggbmV3X3ggKSA9PSAndW5kZWZpbmVkJyApIHsKICAgICAgICBuZXdfeCA9IFtdOwogICAgICAgIGZvciAoIHZhciBpID0gMTsgaSA8PSBrbm93bl95Lmxlbmd0aDsgaSsrICkgbmV3X3gucHVzaChpKTsKICAgIH0KICAgIGlmICggdHlwZW9mKCB1c2VfY29uc3QgKSA9PSAndW5kZWZpbmVkJyApIHVzZV9jb25zdCA9IHRydWU7CgogICAgLy8gY2FsY3VsYXRlIHN1bXMgb3ZlciB0aGUgZGF0YToKICAgIHZhciBuID0ga25vd25feS5sZW5ndGg7CiAgICB2YXIgYXZnX3ggPSAwOyB2YXIgYXZnX3kgPSAwOyB2YXIgYXZnX3h5ID0gMDsgdmFyIGF2Z194eCA9IDA7IAogICAgZm9yICggdmFyIGkgPSAwOyBpIDwgbjsgaSsrICkgewogICAgICAgIHZhciB4ID0ga25vd25feFtpXTsgdmFyIHkgPSBNYXRoLmxvZygga25vd25feVtpXSApOwogICAgICAgIGF2Z194ICs9IHg7IGF2Z195ICs9IHk7IGF2Z194eSArPSB4Knk7IGF2Z194eCArPSB4Kng7CiAgICB9CiAgICBhdmdfeCAvPSBuOyBhdmdfeSAvPSBuOyBhdmdfeHkgLz0gbjsgYXZnX3h4IC89IG47CgogICAgLy8gY29tcHV0ZSBsaW5lYXIgcmVncmVzc2lvbiBjb2VmZmljaWVudHM6CiAgICBpZiAoIHVzZV9jb25zdCApIHsKICAgICAgICB2YXIgYmV0YSA9IChhdmdfeHkgLSBhdmdfeCphdmdfeSkgLyAoYXZnX3h4IC0gYXZnX3gqYXZnX3gpOwogICAgICAgIHZhciBhbHBoYSA9IGF2Z195IC0gYmV0YSphdmdfeDsKICAgIH0gZWxzZSB7CiAgICAgICAgdmFyIGJldGEgPSBhdmdfeHkgLyBhdmdfeHg7CiAgICAgICAgdmFyIGFscGhhID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