淘豆网
1/12
下载文档
0/100
您的浏览器不支持进度条
更多>>该用户其他文档
下载所得到的文件列表
最小二乘法程序.doc
文档介绍:
#include<stdio.h>#include<conio.h>#include<math.h>#include<process.h>#defineN5//N个点#3//T次拟合#defineW1//权函数#definePRECISION0.00001floatpow_n(floata,intn){inti;if(n==0)return(1);floatres=a;for(i=1;i<n;i++){res*=a;}return(res);}voidmutiple(floata[][N],floatb[][T+1],floatc[][T+1]){floatres=0;inti,j,k;for(i=0;i<T+1;i++)for(j=0;j<T+1;j++){res=0;for(k=0;k<N;k++){res+=a[i][k]*b[k][j];c[i][j]=res;}}}voidmatrix_trans(floata[][T+1],floatb[][N]){inti,j;for(i=0;i<N;i++){for(j=0;j<T+1;j++){b[j][i]=a[i][j];}}}voidinit(floatx_y[][2],intn){inti;printf("请输入%d个已知点:\n",N);for(i=0;i<n;i++){printf("(x%dy%d):",i,i);scanf("%f%f",&x_y[i][0],&x_y[i][1]);}}voidget_A(floatmatrix_A[][T+1],floatx_y[][2],intn){inti,j;for(i=0;i<N;i++){for(j=0;j<T+1;j++){matrix_A[i][j]=W*pow_n(x_y[i][0],j);}}}voidprint_array(floatarray[][T+1],intn){inti,j;for(i=0;i<n;i++){for(j=0;j<T+1;j++){printf("%-g",array[i][j]);}printf("\n");}}voidconvert(floatargu[][T+2],intn){inti,j,k,p,t;floatrate,temp;for(i=1;i<n;i++){for(j=i;j<n;j++){if(argu[i-1][i-1]==0){for(p=i;p<n;p++){if(argu[p][i-1]!=0)break;}if(p==n){printf("方程组无解!\n");exit(0);}for(t=0;t<n+1;t++){temp=argu[i-1][t];argu[i-1][t]=argu[p][t];argu[p][t]=temp;}}rate=argu[j][i-1]/argu[i-1][i-1];for(k=i-1;k<n+1;k++){argu[j][k]-=argu[i-1][k]*rate;if(fabs(argu[j][k])<=PRECISION)argu[j][k]=0;}}}}pute(floatargu[][T+2],intn,floatroot[]){inti,j;floattemp;for(i=n-1;i>=0;i--){temp=argu[i][n];for(j=n-1;j>i;j--){temp-=argu[i][j]*root[j];}root[i]=temp/argu[i][i];}}voidget_y(floattrans_A[][N],floatx_y[][2],floaty[],intn){inti,j;floattemp;for(i=0;i<n;i++){temp=0;for(j=0;j<N;j++){temp+=trans_A[i][j]*x_y[j][1];}y[i]=temp;}}voidcons_formula(floatcoef_A[][T+1],floaty[],floatcoef_form[][T+2]){inti,j;for(i=0;i<T+1;i++){for(j=0;j<T+2;j++){if(j==T+1)coef_form[i][j]=y[i];elsecoef_form[i][j]=coef_A[i][j];}}}voidprint_root(floata[],intn){inti,j;printf("%d个点的%d次拟合的多项式系数为:\n",N,T);for(i=0;i<n;i++){printf("a[%d]=%g,",i+1,a[i]);}printf("\n");printf("拟合曲线方程为:\ny(x)=%g",a[0]);for(i=1;i<n;i++){printf("+%g 内容来自淘豆网www.taodocs.com转载请标明出处.