查找“最适合"方程 [英] Find a "best fit" equation

查看:55
本文介绍了查找“最适合"方程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自从我上大学以来已经有一段时间了,知道如何计算最佳拟合线,但是我发现自己需要这样做.假设我有一组要点,我想找到最适合这些要点的线.

It's been a while since I was in college and knew how to calculate a best fit line, but I find myself needing to. Suppose I have a set of points, and I want to find the line that is the best of those points.

确定最佳拟合线的方程是什么? 我将如何使用PHP做到这一点?

What is the equation to determine a best fit line? How would I do that with PHP?

推荐答案

这条线的拟合度可能是另外一个有趣的问题. 为此,请在PHP函数中使用Pearson相关性:

Of additional interest is probably how good of a fit the line is. For that, use the Pearson correlation, here in a PHP function:

/**
 * 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;
}

这篇关于查找“最适合"方程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆