Forecast formula from Excel in Javascript

假如想象 提交于 2019-12-25 09:14:24

问题


I'm trying to make a Forecast function in Javascript based on the code from Excel, explained at https://support.office.com/en-US/article/FORECAST-function-50CA49C9-7B40-4892-94E4-7AD38BBEDA99

But I don't understand what is the x with a trait on top (also y) from the formula and so I don't know how to translate it in Javascript.

Can someone could help me please?

Thank you.


回答1:


x with a trait on top is the mean of x (i.e. the average of all xs). the same is with y. if x values are 20,28,31,38,40 the x with the trait on top is 31.4

function forecast(x, ky, kx){
   var i=0, nr=0, dr=0,ax=0,ay=0,a=0,b=0;
   function average(ar) {
          var r=0;
      for (i=0;i<ar.length;i++){
         r = r+ar[i];
      }
      return r/ar.length;
   }
   ax=average(kx);
   ay=average(ky);
   for (i=0;i<kx.length;i++){
      nr = nr + ((kx[i]-ax) * (ky[i]-ay));
      dr = dr + ((kx[i]-ax)*(kx[i]-ax))
   }
  b=nr/dr;
  a=ay-b*ax;
  return (a+b*x);
}

The above script gives you the forecast without error handling.

You can call this using the below method

forecast(30,[6,7,9,15,21],[20,28,31,38,40]);


来源:https://stackoverflow.com/questions/39373328/forecast-formula-from-excel-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!