线性拟合C语言算法
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
最小二乘法拟合一条直线(C语言代码)
#include
#define N 10 //N为要拟合的数据的个数
float X[10] = {1.9,0.8,1.1,0.1,-0.1,4.4,4.6,1.6,5.5,3.4};
float Y[10] = {0.7,-1.0,-0.2,-1.2,-0.1,3.4,0.0,0.8,3.7,2.0};
float K=0; //拟合直线的斜率
float R=0; //拟合直线的截距
float x_sum_average=0; //数组X[N] 个元素求和并求平均值
float y_sum_average=0; //数组Y[N] 个元素求和并求平均值
float x_square_sum=0; //数组X[N] 个个元素的平均值
float x_multiply_y=0; //数组X[N]和Y[N]对应元素的乘机
float Squre_sum(float c[N]) ;
float Sum_Average(float d[N]);
float X_Y_By(float m[N],float n[N]);
float Squre_sum(float c[N]);
void Line_Fit(void);
void Line_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);
}
float Sum_Average(float d[N])
{
unsigned int i=0;
float z=0;
for(i=0;i { z = z + d[i]; } z = z/N; return z; } float X_Y_By(float m[N],float n[N]) { unsigned int i=0; float z=0; for(i=0;i { z = z + m[i]*n[i]; } return z; } float Squre_sum(float c[N]) { unsigned int i=0; float z=0; for(i=0;i { z = z + c[i]*c[i]; } return z; } void main(void) { Line_Fit(); }