-3

I have been given the following PHP function that returns a trend line using linear regression...

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 < $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"=>$m, "b"=>$b);

}

However, given inputs of...

$x = array(1,2,3,3,4,5,6,7);
$y = array(1,2,3,4,5,6,7,8);

The line plotted in under the points. From what I can tell its because this function minmized the standard deviation rather than the variance. I'm thinking if it did that it would plot the line through the middle. Does anyone have any idea about how to tweak it so it will minimize the variance?

flag
3 
Well, the standard deviation is the square root of the variance... if you minimize one, you minimize the other. So I don't understand what you're actually after... – J. M. Dec 30 2010 at 10:39
Hmm maybe I'm using the wrong terms. Sorry haven't done math since A-level half a decade ago... In the above example, the regression line will plot along the last 5 points as the difference goes (1,1,1,0,0,0,0,0) which sums to 3. However, if you plot between the points you get differences of (-0.5,-0.5,-0.5,0.5,0.5,0.5,0.5,0.5) which sums to 1.5, which would be smaller. I thought it might be using something like SD rather than variance becase it must treat the -0.5s as an absolute value. – unknown (google) Dec 30 2010 at 13:22
Found this on Wikipedia... "This method minimizes the sum of squared vertical distances between the observed responses in the dataset" It's called "Ordinary least squares". I suppose I need it to just minimize the sum of vertical distances. – unknown (google) Dec 30 2010 at 13:40
5 
I believe you're asking in the wrong forum for this type of question. You may find the error in your code's mathematics by possibly asking on math.stackexchange.com, or you may find the error in your mathematic's program code by asking on stackoverflow.com; in either case, please look at the FAQ's and note that what you are asking is not a mathematical research level question. You should either pay a consultant to correct your code for you if you are at work, or you should do your own homework if you are at school. – sleepless in beantown Dec 30 2010 at 14:16
1 
I'm afraid your question is outside the scope of this website, which is focused on research-level questions. Please see the FAQ. – S. Carnahan Dec 31 2010 at 13:15
show 1 more comment

closed as too localized by algori, Andres Caicedo, Yemon Choi, Pete L. Clark, S. Carnahan Dec 31 2010 at 13:14

Browse other questions tagged or ask your own question.