We want to study the error in the difference approximation for forward difference and central difference, tabulate the error for 开发者_如何学运维h=[1.E-3 1.E-4 1.E-5 1.E-6 1.E-7 1.E-8 1.E-9 1.E-10 1.E-11 1.E-12 1.E-13]
and draw a loglog-diagram. Any tips on how to do this?
This is our central- and forward difference.
centdiff=(subs(f, x+h))/(2*h) - (subs(f, x-h))/(2*h)
framdiff=(subs(f, x+h) - f)/h
And our function:
f=60*x-(x.^2+x+0.1).^6./(x+1).^6-10*x.*exp(-x);
The error in the approximation is the difference between the results you get using it, and the analytical result. Luckily, you have a nice function f
, which can easily (well, sorta) be differentiated. After finding the derivative and creating the corresponding Matlab function, you just need to compare the analytical result with the approximate result. The simplest way would probably be using a for
loop over your different h
.
So, the idea is something like this (not tested, just to give you an idea):
cent_error = zeros(size(h));
forw_error = zeros(size(h));
for idx = 1:size(h)
cent_error(idx) = abs(analytical_diff - centdiff(f, h));
forw_error(idx) = abs(analytical_diff - forwdiff(f, h));
end
loglog(...)
精彩评论