求线性回归方程a和b值,结果明显不对
代码如下
#include
//调用库函数
int main() //主函数
{ float aver(float a[],int); //声明求均值函数
float Temp_X[96] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.46667, 11.4667, 31.6, 52.7333, 80.3333, 116.333, 156.6, 199.4, 242.2, 283.4, 329.2, 379.333, 431.333, 482.6, 541, 594.4, 643.533, 692.133, 736.267, 772.667, 810.133, 841.867, 868.2, 892.4, 917.667, 939.8, 954.667, 969, 976.8, 983.4, 987.467, 994.933, 1023.67, 875.2, 873.933, 758.8, 678.2, 515.867, 782.533, 908.8, 779.2, 831.4, 645.533, 734.067, 679.533, 610.267, 565.067, 512.467, 462, 405.2, 354.133, 302, 247.8, 191.533, 140, 94.2667, 57.5333, 25.9333, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; //定义初始化数组X
float Temp_Y[96] = {0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 0.595, 1.785, 2.57833, 3.927, 5.79233, 7.379, 9.48133, 11.1473, 12.4167, 13.6627, 16.193701, 18.248699, 19.042, 19.042, 19.105301, 16.6383, 17.240999, 14.631, 11.8217, 11.663, 12.155, 15.488, 21.859301, 19.32, 19.042, 19.6133, 21.105, 22.9937, 20.827299, 23.858299, 23.0333, 19.2883, 15.6937, 21.5893, 23.802999, 20.518299, 21.5893, 17.907301, 17.971001, 17.574301, 16.781, 15.5513, 12.3773, 10.2747, 8.60867, 6.86333, 5.39567, 3.88767, 2.856, 2.142, 2.142, 0.952, 0.952, 0.952, 0.952, 0.952, 0.952, 0.952, 0.952, 0.952, 0.952, 0.952, 0.952, 0.952, 0.952 }; //定义初始化数组Y
float a,b,sum1=0,sum2=0; //定义变量,a,b为线性回归方程y=ax+b中a,b的值,sum1,sum2,为求a时分步求解用的变量
int i,j; //i,j为循环时使用的变量
for(i=0;i<96;i++)
{
sum1+=(Temp_X[i]*Temp_Y[i]);
sum2+=(Temp_X[i]*Temp_X[i]);
}
a=(sum1-96*aver(Temp_X,96)*aver(Temp_Y,96))/(sum2-96*aver(Temp_X,96)*aver(Temp_X,96)); //通过线性回归方程公式求出a值
b=aver(Temp_Y,96)-(a*aver(Temp_X,96));
printf("a=%f,b=%f",a,b);
}
float aver(float a[],int n) //求均值的函数
{ //用for循环求出所有值的和,再除以个数n
int i;
float sum;
for(i=0;i<n;i++)
{
sum+=a[i];
}
return sum/n; //返回结果
}