美文网首页信息安全专业知识
C++实训--最小二乘法拟合直线

C++实训--最小二乘法拟合直线

作者: 简言之_ | 来源:发表于2019-05-07 18:19 被阅读10次
    #include <iostream>
    using namespace std;
    
    void LinearFit(double abr[],double x[],double y[],int n) {//线性拟合ax+b
       double xsum, ysum,x2sum,xysum;
       xsum = 0; ysum = 0; x2sum = 0; xysum = 0;
       for (int  i = 0; i < n; i++)
       {
           xsum += x[i];
           ysum += y[i];
           x2sum += x[i] * x[i];
           xysum += x[i] * y[i];
       }
       abr[0] = (n*xysum - xsum * ysum) / (n*x2sum - xsum * xsum);//a
       abr[1] = (ysum - abr[0] * xsum) / n;//b
       double yavg = ysum / n;
       double dy2sum1 = 0, dy2sum2 = 0;
       for (int i = 0; i < n; i++)
       {
           dy2sum1 += ((abr[0] * x[i] + abr[1]) - yavg)*((abr[0] * x[i] + abr[1]) - yavg);//r^2的分子
           dy2sum2 += (y[i] - yavg)*(y[i] - yavg);//r^2的分母
       }
       abr[2] = dy2sum1 / dy2sum2;//r^2
    }
    void HalfLogLine(double y[], int n) {//半对数拟合
       for (int i = 0; i < n; i++)
       {
           y[i] = log10(y[i]);
    
       }
    }
    void LogtoLine(double x[], double y[], int n) {//对数拟合
       
       for (int i = 0; i < n; i++)
       {
           y[i] = log(y[i]);
           x[i] = log(x[i]);
           
       }
    }
    int main()
    {
       int const N = 10;//12;
       //double x[N] = {0.96,0.94,0.92,0.90,0.88,0.86,0.84,0.82,0.80,0.78,0.76,0.74 };//半对数
       //double y[N] = {558.0,313.0,174.0,97.0,55.8,31.3,17.4,9.70,5.58,3.13,1.74,1.00 };
       double x[N] = { 0.1,1.0,3.0,5.0,8.0,10.0,20.0,50.0,80.0,100.0 };//对数
       double y[N] = { 0.1,0.9,2.5,4.0,6.3,7.8,14.8,36.0,54.0,67.0 };
       double abr[3];
       //HalfLogLine(y, N);
       LogtoLine(x, y, N);
       LinearFit(abr, x, y, N);
       abr[1] = exp(abr[1]);
       cout << showpos;//显示正负号
       cout <<"相关系数拟合直线:y=" << abr[0] << "x" << abr[1] << endl;
       cout <<"相关系数:r^2"<< abr[2] << endl;
       system("pause");
       return 0;
    }
    

    相关文章

      网友评论

        本文标题:C++实训--最小二乘法拟合直线

        本文链接:https://www.haomeiwen.com/subject/rqvyoqtx.html