A PHP Linear Regression Function
The inspiration for this function came from Fitting Functions to Data: Linear and Exponential Regression miscellaneous on-line topics for Finite Mathematics and Calculus Applied to the Real World.
/**
* linear regression function
* @param $x array x-coords
* @param $y array y-coords
* @returns array() m=>slope, b=>intercept
*/
function linear_regression($x, $y) {
// calculate number points
$n = count($x);
// ensure both arrays of points are the same size
if ($n != count($y)) {
trigger_error("linear_regression(): Number of elements in coordinate arrays do not match.", E_USER_ERROR);
}
// calculate sums
$x_sum = array_sum($x);
$y_sum = array_sum($y);
$xx_sum = 0;
$xy_sum = 0;
for($i = 0; $i < $n; $i++) {
$xy_sum+=($x[$i]*$y[$i]);
$xx_sum+=($x[$i]*$x[$i]);
}
// calculate slope
$m = (($n * $xy_sum) - ($x_sum * $y_sum)) / (($n * $xx_sum) - ($x_sum * $x_sum));
// calculate intercept
$b = ($y_sum - ($m * $x_sum)) / $n;
// return result
return array("m"=>$m, "b"=>$b);
}
Example Usage:
var_dump( linear_regression(array(1, 2, 3, 4), array(1.5, 1.6, 2.1, 3.0)) );

[...] Filtering out the crap so you don’t have to « A PHP Linear Regression Function An ASP.Net Linear Regression Function January 25th,2006 [...]
Richard@Home » Blog Archive » An ASP.Net Linear Regression Function said this on January 25, 2006 at 4:21 pm
On your linear regression code …
I don’t know PHP but I could still follow the action. The parameter equations seem to match my CRC Math Tables.
Thanks for the time saver!
Robb Laney said this on June 14, 2006 at 10:44 pm
hehe, ’tis funny Roob: before I wrote this I couldn’t follow the CRC Math Tables
Richard@Home said this on June 15, 2006 at 8:18 pm
Nice, dude. I had forgotten that it really was this easy. That’ll save me some time.
Benjamin Schmuhl said this on September 6, 2006 at 10:50 pm
Brilliant tutorial.
How would I expand this to do multiple regression on a nonlinear curve?
I would have 1 dependant column and 2 independant columns and at least 5 records of data.
Thanks
Khany said this on January 21, 2007 at 2:29 pm
I used this code to create trendlines in Open Flash Charts.
I was making trendlines from a single set of y-values, though. So I built a couple functions around this. I posted what I did on my site.
Altogether, it returns an array of values that Open Flash Chart can then chart as a straight line. Enjoy.
JakeT said this on February 26, 2008 at 8:38 pm
Hi –
In some cases you could get a Divide by Zero warning so I would make slight change to you code (note I do not do try/catch since PHP wont catch warnings):
$divisor = (($n * $xx_sum) – ($x_sum * $x_sum));
if ($divisor == 0) $m = 0;
else $m = (($n * $xy_sum) – ($x_sum * $y_sum)) / $divisor;
Thank you!
mBird said this on June 8, 2009 at 6:47 pm