Created
October 1, 2012 21:28
-
-
Save oranj/3814545 to your computer and use it in GitHub Desktop.
Best fit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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