您好,欢迎访问三七文档
当前位置:首页 > 办公文档 > 求职简历 > 最小二乘法拟合一条直线(C语言代码)
最小二乘法拟合一条直线(C语言代码)#includestdio.h#defineN9//N为要拟合的数据的个数floatX[9]={1,1.477,1.778,2,2.176,2.301,2.398,2.477,2.638};floatY[9]={7.55,8.02,8.41,8.64,8.75,8.79,8.81,8.83,8.87};floatK=0;//拟合直线的斜率floatR=0;//拟合直线的截距floatx_sum_average=0;//数组X[N]个元素求和并求平均值floaty_sum_average=0;//数组Y[N]个元素求和并求平均值floatx_square_sum=0;//数组X[N]个个元素的平均值floatx_multiply_y=0;//数组X[N]和Y[N]对应元素的乘机floatSqure_sum(floatc[N]);floatSum_Average(floatd[N]);floatX_Y_By(floatm[N],floatn[N]);floatSqure_sum(floatc[N]);voidLine_Fit(void);voidLine_Fit(void){x_sum_average=Sum_Average(X);y_sum_average=Sum_Average(Y);x_square_sum=Squre_sum(X);x_multiply_y=X_Y_By(X,Y);K=(x_multiply_y-N*x_sum_average*y_sum_average)/(x_square_sum-N*x_sum_average*x_sum_average);R=y_sum_average-K*x_sum_average;printf(K=%f\n,K);printf(R=%f\n,R);}floatSum_Average(floatd[N]){unsignedinti=0;floatz=0;for(i=0;iN;i++){z=z+d[i];}z=z/N;returnz;}floatX_Y_By(floatm[N],floatn[N]){unsignedinti=0;floatz=0;for(i=0;iN;i++){z=z+m[i]*n[i];}returnz;}floatSqure_sum(floatc[N]){unsignedinti=0;floatz=0;for(i=0;iN;i++){z=z+c[i]*c[i];}returnz;}voidmain(void){Line_Fit();}
本文标题:最小二乘法拟合一条直线(C语言代码)
链接地址:https://www.777doc.com/doc-5302887 .html