本文档提供了牛顿法、列主元素消去法、LU分解法三类求解方程的代码,对应非线性方程及线性方程组。利用C语言编写,采用txt文件输入、输出方式。/*牛顿法求解非线性方程*/#includestdio.h#includemath.h#includestdlib.hfloatf(floatx)/*定义函数f(x)*/{return2*x*x+2*x+1-exp(2*x);}floatf1(floatx)/*定义函数f(x)的导数f1(x)*/{return4*x+2-2*exp(2*x);}main(){floatx0,x1,eps;/*定义初值和迭代精度*/FILE*fp1,*fp2;if((fp1=fopen(in.txt,r))==NULL){printf(Can'topenthisfile!\n);exit(0);}fscanf(fp1,%f%f,&x1,&eps);do{x0=x1;if(fabs(f(x0))=eps)x1=x0;elsex1=x0-f(x0)/f1(x0);/*牛顿迭代*/}while(fabs(f(x1))eps);/*循环条件*/fp2=fopen(out.txt,w);fprintf(fp2,%e,x1);fclose(fp1);fclose(fp2);}/*列主元素消去法求解线性方程组*/#includestdio.h#includemath.h#includestdlib.h#defineN3voidmain(){inti,j,k,mi;/*定义变量类型*/floatmax,temp;floata[N][N],b[N],x[N],r[N][N+1];FILE*fp1;/*输入系数矩阵及列向量b*/if((fp1=fopen(in.txt,r))==NULL){printf(Can'topenthisfile!\n);exit(0);}for(i=0;iN;i++)for(j=0;jN+1;j++)fscanf(fp1,%f,&r[i][j]);fclose(fp1);for(i=0;iN;i++)for(j=0;jN;j++)a[i][j]=r[i][j];for(i=0;iN;i++)b[i]=r[i][N];for(j=0;jN-1;j++)/*找出列主元素并交换*/{for(i=j+1,mi=j,max=fabs(a[j][j]);iN;i++)if(fabs(a[i][j])max){mi=i;max=fabs(a[i][j]);}if(jmi){temp=b[j];b[j]=b[mi];b[mi]=temp;for(k=j;kN;k++){temp=a[j][k];a[j][k]=a[mi][k];a[mi][k]=temp;}}for(i=j+1;iN;i++){temp=-a[i][j]/a[j][j];b[i]+=b[j]*temp;for(k=j;kN;k++)a[i][k]+=a[j][k]*temp;}}x[N-1]=b[N-1]/a[N-1][N-1];/*消去求解*/for(i=N-2;i=0;i--){x[i]=b[i];for(j=i+1;jN;j++)x[i]-=a[i][j]*x[j];x[i]/=a[i][i];}FILE*fp2;fp2=fopen(out.txt,w);for(i=0;iN;i++)fprintf(fp2,x[%d]=%f\n,i+1,x[i]);fclose(fp2);}/*线性方程组的LU分解法*/#includestdio.h#includemath.h#includestdlib.h#defineN3voidmain(){inti,j,k,n;floattemp;floata[N][N],b[N],x[N],y[N],L[N][N],U[N][N],r[N][N+1];FILE*fp1;if((fp1=fopen(in.txt,r))==NULL){printf(Can'topenthisfile!\n);exit(0);}for(i=0;iN;i++)for(j=0;jN+1;j++)fscanf(fp1,%f,&r[i][j]);fclose(fp1);for(i=0;iN;i++)for(j=0;jN;j++)a[i][j]=r[i][j];for(i=0;iN;i++)b[i]=r[i][N];for(i=0;iN;i++)/*矩阵分解*/{U[0][i]=a[0][i];L[i][i]=1.0;L[i][0]=a[i][0]/a[0][0];for(j=i+1;jN;j++){L[i][j]=0;U[j][i]=0;}}for(i=1;iN;i++){for(j=i;jN;j++){temp=0;for(k=0;ki;k++)temp=temp+L[i][k]*U[k][j];U[i][j]=a[i][j]-temp;}for(j=i;jN;j++){temp=0;for(k=0;ki;k++)temp=temp+L[j][k]*U[k][i];L[j][i]=(a[j][i]-temp)/U[i][i];}}y[0]=b[0];/*解该线性方程组*/for(i=1;iN;i++){temp=0;for(j=0;ji;j++)temp=temp+L[i][j]*y[j];y[i]=b[i]-temp;}x[N-1]=y[N-1]/U[N-1][N-1];for(i=N-2;i=0;i--){x[i]=y[i];for(j=i+1;jN;j++)x[i]-=U[i][j]*x[j];x[i]/=U[i][i];}FILE*fp2;fp2=fopen(out.txt,w);for(i=0;iN;i++)fprintf(fp2,x[%d]=%f\n,i+1,x[i]);fclose(fp2);}