数值分析中求解非线性方程的MATLAB求解程序(6种)1.求解不动点function[k,p,err,P]=fixpt(g,p0,tol,max1)%求解方程x=g(x)的近似值,初始值为p0%迭代式为Pn+1=g(Pn)%迭代条件为:在迭代范围内满足|k|1(根及附近且包含初值)k为斜率P(1)=p0;fork=2:max1P(k)=feval(g,P(k-1));err=abs(P(k)-P(k-1));relerr=err/(abs(P(k))+eps);p=P(k);if(errtol)|(relerrtol)break;endendifk==max1disp('超过了最长的迭代次数')endP=P';2.二分法function[c,err,yc]=bisect(f,a,b,delta)%二分法求解非线性方程ya=feval(f,a);yb=feval(f,b);ifya*yb0break;endmax1=1+round((log(b-a)-log(delta))/log(2));fork=1:max1c=(a+b)/2;yc=feval(f,c);ifyc==0a=c;b=c;elseifyb*yc0b=c;yb=yc;elsea=c;ya=yc;endifb-adeltabreak;endendc=(a+b)/2;err=abs(b-a);yc=feval(f,c);3.试值法function[c,err,yc]=regula(f,a,b,delta,epsilon,max1)%试值法求解非线性方程%f(a)和飞(b)异号ya=feval(f,a);yb=feval(f,b);ifya*yb0disp('Note:f(a)*f(b)0');endfork=1:max1dx=yb*(b-a)/(yb-ya);c=b-dx;ac=c-a;yc=feval(f,c);ifyc==0break;elseifyb*yc0b=c;yb=yc;elsea=c;ya=yc;enddx=min(abs(dx),ac);ifabs(dx)delta|abs(yc)epsilonbreak;endendc;err=abs(b-a)/2;yc=feval(f,c);4.求解非线性方程根的近似位置functionR=approot(X,epsilon)%求解根近似位置%为了粗估算方程f(x)=0在区间[a,b]的根的位置,%使用等间隔采样点(xk,f(xk))和如下的评定准则:%f(xk-1)与f(xk)符号相反,%或者|f(xk)|足够小且曲线y=f(x)的斜率在%(xk,f(xk))附近改变符号。Y=f(X);yrange=max(Y)-min(Y);epsilon2=yrange*epsilon;n=length(X);m=0;X(n+1)=X(n);Y(n+1)=Y(n);fork=2:nifY(k-1)*Y(k)0m=m+1;R(m)=(X(k-1)+X(k))/2;ends=(Y(k)-Y(k-1))*(Y(k+1)-Y(k));if(abs(Y(k))epsilon2)&(s=0)m=m+1;R(m)=X(k);endend5.牛顿—拉夫森迭代function[p0,err,k,y]=newton(f,df,p0,delta,epsilon,max1)%牛顿—拉夫森迭代求解非线性方程%df需要自己f手动求得%p0为迭代初始值,max1为最大迭代次数fork=1:max1p1=p0-feval(f,p0)/feval(df,p0);err=abs(p1-p0);relerr=2*err/(abs(p1)+delta);p0=p1;y=feval(f,p0);if(errdelta)|(relerrdelta)|(abs(y)epsilon)breakendend6.割线法function[p1,err,k,y]=secant(f,p0,p1,delta,epsilon,max1)%割线法迭代求解非线性方程fork=1:max1p2=p1-feval(f,p1)*(p1-p0)/(feval(f,p1)-feval(f,p0));err=abs(p2-p1);relerr=2*err/(abs(p2)+delta);p0=p1;p1=p2;y=feval(f,p1);if(errdelta)|(relerrdelta)|(abs(y)epsilon)break;endend