为什么80%的码农都做不了架构师?>>>
/*** 简单线性回归算法* @param array y轴数据* @param array x轴数据* @returns array(slope,intercept,r2)*/
function linearRegression(y, x) {var lr = {};var n = y.length;var sum_x = 0;var sum_y = 0;var sum_xy = 0;var sum_xx = 0;var sum_yy = 0;for (var i = 0; i < y.length; i++) {sum_x += x[i];sum_y += y[i];sum_xy += (x[i] * y[i]);sum_xx += (x[i] * x[i]);sum_yy += (y[i] * y[i]);}lr['slope'] = (n * sum_xy - sum_x * sum_y) / (n * sum_xx - sum_x * sum_x);lr['intercept'] = (sum_y - lr.slope * sum_x) / n;lr['r2'] = Math.pow((n * sum_xy - sum_x * sum_y) / Math.sqrt((n * sum_xx - sum_x * sum_x) * (n * sum_yy - sum_y * sum_y)), 2);return lr;};
算法详解:http://wiki.mbalib.com/wiki/%E4%B8%80%E5%85%83%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92%E9%A2%84%E6%B5%8B%E6%B3%95
b=slope,a=intercept
y=a+bx