如何使用c ++获得线性回归线的斜率? [英] how to get the slope of a linear regression line using c++?

查看:862
本文介绍了如何使用c ++获得线性回归线的斜率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要达到类似于下面链接中的excel函数的线性回归的斜率:

I need to attain the slop of a linear regression similar to the way the excel function in the below link is implemented:

http://office.microsoft.com/en-gb/excel-help/slope-function-HP010342903.aspx

有没有一个C ++库或一个简单的编码解决方案有人创建的可以做到这一点?
我已经根据这个公式实现代码,但它并不总是给我正确的结果(从这里取得 http://easycalculation.com/statistics/learn-regression.php )...

Is there a library in C++ or a simple coded solution someone has created which can do this? I have implemented code according to this formula, however it does not always give me the correct results (taken from here http://easycalculation.com/statistics/learn-regression.php) ....

Slope(b) = (NΣXY - (ΣX)(ΣY)) / (NΣX2 - (ΣX)2)
         = ((5)*(1159.7)-(311)*(18.6))/((5)*(19359)-(311)2)
         = (5798.5 - 5784.6)/(96795 - 96721)
         = 13.9/74
         = 0.19 

如果我试图对以下向量,我得到错误的结果(我应该期待0.305556):
x = 6 ,5,11,7,5,4,4
y = 2,3,9,1,8,7,5

If i try it against the following vectors, i get the wrong results (i should be expecting 0.305556): x = 6,5,11,7,5,4,4 y = 2,3,9,1,8,7,5

提前感谢

推荐答案

为什么你不是这样编写一个简单的代码(不是最好的解决方案,帮助文章):

Why don't you just write a simple code like this (not the best solution, for sure, just an example based on the help article):

double slope(const vector<double>& x, const vector<double>& y){
    if(x.size() != y.size()){
        throw exception("...");
    }
    double n = x.size();

    double avgX = accumulate(x.begin(), x.end(), 0.0) / n;
    double avgY = accumulate(y.begin(), y.end(), 0.0) / n;

    double numerator = 0.0;
    double denominator = 0.0;

    for(int i=0; i<n; ++i){
        numerator += (x[i] - avgX) * (y[i] - avgY);
        denominator += (x[i] - avgX) * (x[i] - avgX);
    }

    if(denominator == 0){
        throw exception("...");
    }

    return numerator / denominator;
}

注意,accumulate函数的第三个参数必须是0.0而不是0,否则编译器将扣除其类型为int,并且有很大机会累加调用的结果将是错误的(使用MSVC2010和mingw-w64当传递0作为第三个参数时实际上是错误的)。

Note that the third argument of accumulate function must be 0.0 rather than 0, otherwise compiler will deduct its type as int and there are great chances that the result of accumulate calls will be wrong (it's actually wrong using MSVC2010 and mingw-w64 when passing 0 as the third parameter).

这篇关于如何使用c ++获得线性回归线的斜率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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