最小二乘法拟合二次曲线 C语言

题目

X[21] = {0.00,0.056,0.112,0.168,0.224,0.280,0.336,0.392,0.448,0.504,0.560,0.616,0.672,0.728,0.784,0.84,0.896,0.952,1.008,1.064,1.12}

Y[21] =

{0.00,1.66,3.31,4.96,6.6,8.22,9.82,11.4,12.94,14.43,15.86,17.22,18.5,19.69,20.79,21.79,22.71,23.53,24.25,24.87,25.4}

利用最小二乘法将上面数据所标示的曲线拟合为二次曲线,使用c语言编程求解函数系数;

最小二乘法原理

原理不再赘述,主要是解法采用偏微分求出来的系数公式a,b,c

最小二乘法拟合二次曲线 C语言_第1张图片

最小二乘法拟合二次曲线 C语言_第2张图片
最小二乘法拟合二次曲线 C语言_第3张图片
就是这个公式,对应了二次方程的a,b,c
#include
#include 
#define N 1e-13
int  main()
{
double x[21]={0.00,0.056,0.112,0.168,0.224,0.280,0.336,0.392,0.448,0.504,0.560,0.616,0.672,0.728,0.784,0.84,0.896,0.952,0.1008,0.1064,1.12};
double y[21]={0.00,1.66,3.31,4.96,6.6,8.22,9.82,11.4,12.94,14.43,15.86,17.22,18.5,19.69,20.79,21.79,22.7,23.53,24.25,24.87,25.4};
double a,b,c,m1,m2,m3,z1,z2,z3;a=b=c=0;
double sumx=0,sumx2=0,sumx3=0,sumx4=0,sumy=0,sumxy=0,sumx2y=0;
for(int i=0;i<21;i++)
{
sumx+=x[i];sumy+=y[i];
sumx2+=pow (x[i],2); sumxy+=x[i]*y[i];
sumx3+=pow(x[i],3); sumx2y+=pow(x[i],2)*y[i];
sumx4+=pow(x[i],4);
}
do{
m1=a; a=(sumx2y-sumx3*b-sumx2*c)/sumx4; z1=(a-m1)*(a-m1);
m2=b; b=(sumxy-sumx*c-sumx3*a)/sumx2; z2=(b-m2)*(b-m2);
m3=c; c=(sumy-sumx2*a-sumx*b)/42; z3=(c-m3)*(c-m3);
}while((z1>N)||(z2>N)||(z3>N));
printf("a=%9.6f,\nb=%9.6f,\nc=%9.6f\n",a,b,c);
printf ("拟合方程为   y=%9.6fx*x+%9.6fx+%9.6f",a,b,c);
return 0;
}


你可能感兴趣的:(最小二乘法拟合二次曲线 C语言)