Zend - The PHP Company




Math

Add Code


Linear Regression  

Type: class
Added by: mathie
Entered: 04/02/2006
Last modified: 02/12/2005
Rating: - (fewer than 3 votes)
Views: 3347
Simple linear regression class


<?php
/** 
* @author Son Nguyen
* @since 11/18/2005
* @package Framework.Data
* @subpackage Math
*/
class CRegressionLinear {
 private 
$mDatas;
 
/** constructor */
 
function __construct($pDatas) {
  
$this->mDatas $pDatas;
 }

 
/** get the coefficients */
 
function calculate() {
  
$n count($this->mDatas);
  
$vSumXX $vSumXY $vSumX $vSumY 0;
  foreach (
$this->mDatas AS $x=>$y) {
   
$vSumXY += $x*$y;
   
$vSumXX += $x*$x;
   
$vSumX += $x;
   
$vSumY += $y;
  } 
// rof
  
$a = ($n*$vSumXY $vSumX*$vSumY)/($n*$vSumXX $vSumX*$vSumX);

  
$b = ($vSumY $a*$vSumX)/$n;
  return array(
$a,$b);
 }

 
/** given x, return the prediction */
 
function predict($x) {
  list(
$a,$b) = $this->calculate();
  
$y $a*$x+$b;
  return 
$y;
 }
}
?>


Usage Example


See the example


Rate This Script





Search



This Category All Categories