Last active
May 7, 2021 07:48
-
-
Save greydnls/a7c479accd97a7cabade to your computer and use it in GitHub Desktop.
Least Squares Method
This file contains hidden or 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
<?php | |
/** | |
* Created by PhpStorm. | |
* User: kayladnls | |
* Date: 12/19/14 | |
* Time: 4:20 PM | |
*/ | |
$x = [1, 2, 3, 4, 5]; | |
$y = [2, 4, 5, 4, 5]; | |
$barx = []; | |
$bary = []; | |
$mean_x = calculateMean($x); | |
$mean_y = calculateMean($y); | |
$mean_intercept = [$mean_x, $mean_y]; | |
//calculate x - barx | |
foreach ($x as $idx => $point) | |
{ | |
$barx[$idx] = $point - $mean_x; | |
} | |
//calculate y - bary | |
foreach ($y as $idx => $point) | |
{ | |
$bary[$idx] = $point - $mean_y; | |
} | |
$slope = findSlope($barx, $bary); | |
$yint = calcYInt($slope, $mean_intercept); | |
function calcYInt($slope, $mean_intercept) | |
{ | |
return $mean_intercept[1] - ($slope * $mean_intercept[0]); | |
} | |
function yhat($x, $yint, $slope) | |
{ | |
return $yint + ($slope * $x); | |
} | |
function findSlope($barx, $bary) | |
{ | |
$barxsq = squareArr($barx); | |
$barx_times_bary = multArrs($barx, $bary); | |
return calcSum($barx_times_bary) / calcSum($barxsq); | |
} | |
function multArrs($array1, $arry2) | |
{ | |
$multiplied = []; | |
foreach ($array1 as $idx => $first) | |
{ | |
$multiplied[] = $first * $arry2[$idx]; | |
} | |
return $multiplied; | |
} | |
function squareArr(array $vals) | |
{ | |
$return = []; | |
foreach ($vals as $val) | |
{ | |
$return[] = $val*$val; | |
} | |
return $return; | |
} | |
function calculateMean(array $vals) | |
{ | |
return calcSum($vals) / count($vals); | |
} | |
function calcSum(array $vals) | |
{ | |
$sum = 0; | |
foreach ($vals as $val) | |
{ | |
$sum += $val; | |
} | |
return $sum; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment