fork(13) download
  1. function growth ( known_y, known_x, new_x, use_const ) {
  2. // default values for optional parameters:
  3. if ( typeof( known_x ) == 'undefined' ) {
  4. known_x = [];
  5. for ( var i = 1; i <= known_y.length; i++ ) known_x.push(i);
  6. }
  7. if ( typeof( new_x ) == 'undefined' ) {
  8. new_x = [];
  9. for ( var i = 1; i <= known_y.length; i++ ) new_x.push(i);
  10. }
  11. if ( typeof( use_const ) == 'undefined' ) use_const = true;
  12.  
  13. // calculate sums over the data:
  14. var n = known_y.length;
  15. var avg_x = 0; var avg_y = 0; var avg_xy = 0; var avg_xx = 0;
  16. for ( var i = 0; i < n; i++ ) {
  17. var x = known_x[i]; var y = Math.log( known_y[i] );
  18. avg_x += x; avg_y += y; avg_xy += x*y; avg_xx += x*x;
  19. }
  20. avg_x /= n; avg_y /= n; avg_xy /= n; avg_xx /= n;
  21.  
  22. // compute linear regression coefficients:
  23. if ( use_const ) {
  24. var beta = (avg_xy - avg_x*avg_y) / (avg_xx - avg_x*avg_x);
  25. var alpha = avg_y - beta*avg_x;
  26. } else {
  27. var beta = avg_xy / avg_xx;
  28. var alpha = 0;
  29. }
  30. // console.log("alpha = " + alpha + ", beta = " + beta);
  31.  
  32. // compute and return result array:
  33. var new_y = [];
  34. for ( var i = 0; i < new_x.length; i++ ) {
  35. new_y.push( Math.exp( alpha + beta * new_x[i] ) );
  36. }
  37. return new_y;
  38. }
  39.  
  40. // demo data from http://office.microsoft.com/en-us/excel-help/growth-function-HA102753003.aspx
  41. var known_y = [33100, 47300, 69000, 102000, 150000, 220000];
  42. var known_x = [11, 12, 13, 14, 15, 16];
  43. var new_x = [11, 12, 13, 14, 15, 16, 17, 18, 19];
  44. var new_y = growth( known_y, known_x, new_x );
  45.  
  46. for ( var i = 0; i < new_x.length; i++ ) {
  47. print( new_x[i] + ": " + new_y[i] );
  48. }
Success #stdin #stdout 0.01s 4940KB
stdin
Standard input is empty
stdout
11: 32618.203773538437
12: 47729.42261474665
13: 69841.30085621694
14: 102197.07337883314
15: 149542.4867400494
16: 218821.87621460424
17: 320196.7183634903
18: 468536.05418408214
19: 685597.3889812973