php如何用最小二乘法拟合二元一次方程 计算方程的X和Y值

下面是R语言的实现函数可以直接计算出结果

x<-c(20,40,60,80,100)
y<-c(3,6.5,9.1,12.1,15.3)
lsfit(x,y)

php如何用最小二乘法拟合二元一次方程 计算方程的X和Y值

请问php有没有类似的类库,或者哪位大哥指点一下这个怎么搞。。。脑子都炸了 csdn 啥也不是

VeryCool
讨论数量: 2

如果是扩展,没有。

如果是composer包,那和自己写个func没啥区别。

1年前 评论
function linearRegression($x, $y) {
    $n = count($x);
    $sum_x = array_sum($x);
    $sum_y = array_sum($y);
    $sum_xy = dotProduct($x, $y);
    $sum_xx = dotProduct($x, $x);

    $slope = ($sum_xy - ($sum_x * $sum_y) / $n) / ($sum_xx - ($sum_x * $sum_x) / $n);
    $intercept = $sum_y / $n - $slope * $sum_x / $n;

    return [$slope, $intercept];
}

function dotProduct($x, $y) {
    $result = 0;
    $n = count($x);
    for ($i = 0; $i < $n; $i++) {
        $result += $x[$i] * $y[$i];
    }
    return $result;
}

$x = array(20,40,60,80,100);
$y = array(3,6.5,9.1,12.1,15.3);

list($slope, $intercept) = linearRegression($x, $y);

echo "Slope: $slope\n";
echo "Intercept: $intercept\n";
1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!