Skip to content

Instantly share code, notes, and snippets.

@ursuleacv
Created September 10, 2023 19:47
Show Gist options
  • Save ursuleacv/f68c326a2488579d3a23164577cee1fc to your computer and use it in GitHub Desktop.
Save ursuleacv/f68c326a2488579d3a23164577cee1fc to your computer and use it in GitHub Desktop.
Calculate quadratic polynomial regression
<?php
function quadraticRegression($dataPoints) {
$sumX = 0;
$sumX2 = 0;
$sumX3 = 0;
$sumX4 = 0;
$sumY = 0;
$sumXY = 0;
$sumX2Y = 0;
$n = count($dataPoints);
foreach ($dataPoints as $dataPoint) {
$x = $dataPoint[0];
$y = $dataPoint[1];
$sumX += $x;
$sumX2 += pow($x, 2);
$sumX3 += pow($x, 3);
$sumX4 += pow($x, 4);
$sumY += $y;
$sumXY += $x * $y;
$sumX2Y += pow($x, 2) * $y;
}
$matrix = [
[$sumX4, $sumX3, $sumX2],
[$sumX3, $sumX2, $sumX],
[$sumX2, $sumX, $n]
];
$vector = [
$sumX2Y,
$sumXY,
$sumY
];
$coefficients = solveLinearSystem($matrix, $vector);
return $coefficients;
}
function solveLinearSystem($matrix, $vector) {
$n = count($matrix);
for ($i = 0; $i < $n; $i++) {
$pivot = $matrix[$i][$i];
for ($j = $i; $j < $n; $j++) {
$matrix[$i][$j] /= $pivot;
}
$vector[$i] /= $pivot;
for ($k = 0; $k < $n; $k++) {
if ($k != $i) {
$factor = $matrix[$k][$i];
for ($j = $i; $j < $n; $j++) {
$matrix[$k][$j] -= $factor * $matrix[$i][$j];
}
$vector[$k] -= $factor * $vector[$i];
}
}
}
return array_slice($vector, 0, $n);
}
$dataPoints = [
[1, 3],
[2, 8],
[3, 12],
[4, 20],
[5, 30]
];
$coefficients = quadraticRegression($dataPoints);
$a = $coefficients[0];
$b = $coefficients[1];
$c = $coefficients[2];
echo "The quadratic polynomial is: y = $a * x^2 + $b * x + $c";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment