Skip to content

Instantly share code, notes, and snippets.

@oranj
Created October 1, 2012 21:28
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save oranj/3814545 to your computer and use it in GitHub Desktop.
Best fit
function calculate_line($x1, $y1, $x2, $y2, $dataset) {
$m = ($y2 - $y1) / ($x2 - $x1);
$b = ($y1 - $m * $x1);
$total_diff = 0;
foreach ($dataset as $inf) {
list($x, $y) = $inf;
$yl = $m * $x + $b;
$diff[$x] = $yl - $y;
$total_diff += abs($diff[$x]);
}
return array('m' => $m, 'b' => $b, 'diff' => $diff, 'total_diff' => $total_diff);
}
function best_fit($dataset) {
$data = array();
$smallest_key = '';
$smallest_val = INF;
for ($i = 0; $i < count($dataset) - 1; $i++) {
for ($j = $i + 1; $j < count($dataset); $j++) {
list($x1, $y1) = $dataset[$i];
list($x2, $y2) = $dataset[$j];
$key = "$i :: $j";
$data[$key] = calculate_line($x1, $y1, $x2, $y2, $dataset);
$val = $data[$key]['total_diff'];
if ($val < $smallest_val) {
$smallest_val = $val;
$smallest_key = $key;
}
}
}
return $data[$smallest_key];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment