title: How do I improve this linear regression function?
body: <p>I have the following PHP function that I'm using to draw a trend line. However, it sometimes plots the line below all the points in the scatter graph. Is there an error in my function or is there a better way to do it. I think it might be something to do with that with the line it produces, it treats all the residuals (the distances from the scatter points to the line) as positive regardless of them being above or below the line.</p>
  
  <pre><code>function linear_regression($x, $y) {
  
  $n = count($x);
  
  $x_sum = array_sum($x); $y_sum = array_sum($y);
  
  $xx_sum = 0; $xy_sum = 0;
  
  for($i = 0; $i &lt; $n; $i++) { $xy_sum+=($x[$i]*$y[$i]); $xx_sum+=($x[$i]*$x[$i]); }
  
  $m = (($n * $xy_sum) - ($x_sum * $y_sum)) / (($n * $xx_sum) - ($x_sum * $x_sum)); $b = ($y_sum - ($m * $x_sum)) / $n; return array("m"=&gt;$m, "b"=&gt;$b);
  
  }
  </code></pre>