找到"最合适"的方程式

dav*_*gr8 12 php math

我在大学时已经有一段时间知道如何计算出最合适的线条,但我发现自己需要这样做.假设我有一组点,我想找到这些点中最好的一条线.

确定最佳拟合线的公式是什么?我怎么用PHP做到这一点?

Joh*_*ook 6

这是一篇比较两种方法来匹配数据的文章.需要注意的一点是,理论上有一个直接的解决方案,但可能存在数值问题.文章说明了为什么该方法可能失败并提供另一种更好的方法.


use*_*636 5

最小二乘法 http://en.wikipedia.org/wiki/Least_squares.本书" 数字食谱第3版:科学计算的艺术(精装)" 拥有实现最小二乘法和其他技术的算法所需的一切.


ruq*_*uay 3

更令人感兴趣的可能是这条线的贴合度有多好。为此,请在 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)