最小二乘曲线拟合——C语言算法实现二

最小二乘曲线拟合

   在上一篇博客中我们介绍了最小二乘法的原理,以及代码实现的例子。

      http://blog.csdn.net/beijingmake209/article/details/27565125

   本次我们再给出一个程序实现的例子。编译环境VC6.0

  先给出一组需要拟合的数据:

  xx[]=  { 0.995119, 2.001185, 2.999068, 4.001035, 4.999859, 6.004461, 6.999335, 7.999433,

             9.002257, 10.003888, 11.004076, 12.001602, 13.003390, 14.001623, 15.003034,  
             16.002561, 17.003010, 18.003897, 19.002563, 20.003530};
 yy[] = { -7.6200, -2.460, 108.7600, 625.020, 2170.500, 5814.5800,13191.8400,26622.060,

            49230.2200, 85066.5000, 139226.2800, 217970.1400, 328843.8600,480798.4200,

            684310.00, 951499.9800, 1296254.9400, 1734346.6600, 2283552.1200, 2963773.50};

可以调节 拟合数据xx[] yy[]空间大小和dimension 多项式的阶数以适应应用场景。

实现代码如下:

#include 
#include 
 
#include "math.h"
 
void polyfit(int n, double *x, double *y, int poly_n, double p[]);
void gauss_solve(int n,double A[],double x[],double b[]);
 
/*==================polyfit(n,x,y,poly_n,a)===================*/
/*=======拟合y=a0+a1*x+a2*x^2+……+apoly_n*x^poly_n========*/
/*=====n是数据个数 xy是数据值 poly_n是多项式的项数======*/
/*===返回a0,a1,a2,……a[poly_n],系数比项数多一(常数项)=====*/
void polyfit(int n,double x[],double y[],int poly_n,double p[])
{
	int i,j;
	double *tempx,*tempy,*sumxx,*sumxy,*ata;
	
	tempx = (double *)calloc(n , sizeof(double));
	sumxx = (double *)calloc((poly_n*2+1) , sizeof(double));
	tempy = (double *)calloc(n , sizeof(double));
	sumxy = (double *)calloc((poly_n+1) , sizeof(double));
	ata = (double *)calloc( (poly_n+1)*(poly_n+1) , sizeof(double) );
	for (i=0;i=0;x[i]/=A[i*n+i],i--)
	{
		for (j=i+1,x[i]=b[i];j

 拟合结果如下所示:

  拟合系数, 按升序排列如下:
 P[0]=-18.544118
 P[1]=6.725933
 P[2]=0.236626
 P[3]=-0.529331
 P[4]=-1.450258
 P[5]=0.999157

 

 

 

你可能感兴趣的:(STM32,算法)