数值计算求导数

求导数

公式是直接给出来,可以看第四个课件里面给的公式

x0=0.6;h=0.1;
df2=(f(x0)-f(x0-h))/h
df3=1/2/h*(-3*f(x0)+4*f(x0+h)-f(x0+2*h))%在Matlab中表示1/2h的时候是1/2/h
df3M=1/2/h*(f(x0+h)-f(x0-h))
df5M=1/12/h*(f(x0-2*h)-8*f(x0-h)+8*f(x0+h)-f(x0+2*h))
function y = f(x)
y=(x/(1+x))^5;
end

我们再来看看这几种方法求的的导数值和真实值的误差,然后把图画出来

x0=0.6;
h=logspace(-5,1,100); df=0.0386238098144531;%要画图,所以要取足够多的点
FD2P=abs(df-(f(x0)-f(x0-h))./h);
FD3PE=abs(df-1./2./h.*(-3*f(x0)+4.*f(x0+h)-f(x0+2.*h)));
FD3PM=abs(df-1./2./h.*(f(x0+h)-f(x0-h)));
FD5PM=abs(df-1./12./h.*(f(x0-2.*h)-8.*f(x0-h)+8.*f(x0+h)-f(x0+2.*h)));
loglog(h,FD2P,'b'),hold on
loglog(h,FD3PE,'r'),hold on
loglog(h,FD3PM,'y'),hold on
loglog(h,FD5PM,'c'),hold on
loglog(h,h,'k-.'),hold on
loglog(h,h.*h,'k--'),hold on
loglog(h,h.^4,'k'),hold on
xlabel('h'),ylabel('Fehler')
axis([10^-5,1,10^-20,10^10])
legend({'Zweipunkte-Formel','Dreipunkte-Endpunkt-Formel','Dreipunkte-Mittelpunkt-Formel','Fünfpunkte-Mittelpunkt-Formel','h','h^2','h^4'},'Location','northwest')
function y = f(x)
y=(x./(1+x)).^5;
 end

 

你可能感兴趣的:(matlab)