我在大学时已经有一段时间知道如何计算出最合适的线条,但我发现自己需要这样做.假设我有一组点,我想找到这些点中最好的一条线.
确定最佳拟合线的公式是什么?我怎么用PHP做到这一点?
更令人感兴趣的可能是这条线的贴合度有多好。为此,请在 PHP 函数中使用 Pearson 相关性:
/**
* returns the pearson correlation coefficient (least squares best fit line)
*
* @param array $x array of all x vals
* @param array $y array of all y vals
*/
function pearson(array $x, array $y)
{
// number of values
$n = count($x);
$keys = array_keys(array_intersect_key($x, $y));
// get all needed values as we step through the common keys
$x_sum = 0;
$y_sum = 0;
$x_sum_sq = 0;
$y_sum_sq = 0;
$prod_sum = 0;
foreach($keys as $k)
{
$x_sum += $x[$k];
$y_sum += $y[$k];
$x_sum_sq += pow($x[$k], 2);
$y_sum_sq += pow($y[$k], 2);
$prod_sum += $x[$k] * $y[$k];
}
$numerator = $prod_sum - ($x_sum * $y_sum / $n);
$denominator = sqrt( ($x_sum_sq - pow($x_sum, 2) / $n) * ($y_sum_sq - pow($y_sum, 2) / $n) );
return $denominator == 0 ? 0 : $numerator / $denominator;
}
Run Code Online (Sandbox Code Playgroud)