0
$\begingroup$

im trying to plot the approximated error of a function f(x)=cos(x) at x0=pi/4 and take the absolute error between the exact value and approximated value of f'(x) = (f(x0+h)-f(x0-h))/2h ...

my code is as below:

f=@(x)cos(x)
f_exact=-sin(x0) \% this is the exact f'(x0) 
x0=pi/4;
for i=1:21;
    h=10^(1-i);
    f_approx=(f(x0+h)-f(x0-h))./(2*h);
    err=abs(f_approx-f_exact);
    d_error=abs(((h^2)*sin(x0))./6);
end
plot(h,err);
loglog(h,err);

i cant get anything on my matlab, just iterated values of h=10^(i). a blank graph is generated. im still very new to matlab and programming, is there something im missing or something which i should define in/out of the for loop?

appreciated!

$\endgroup$
1
  • $\begingroup$ I have not used loglog very much, but in matlab you need a "hold on;" command to not erase the previous draw commands done in the current figure. $\endgroup$ Sep 27, 2015 at 16:23

1 Answer 1

0
$\begingroup$

First of all, you need to define x0 before you use it. Then you are just plotting a single point each time which is visible but only one pixel. I recommend using

plot(h,err,'o-');
loglog(h,err,'o-');

This shows you where the points are. As @mathreadler pointed out, if you want to see all points of each iteration, you have to plug the plot commands into the loop and use hold, or you save the results for each $i$ in a vector:

f=@(x)cos(x)
x0=pi/4;
f_exact=-sin(x0)

for i=1:21;
    h(i)=10^(1-i);
    f_approx=(f(x0+h(i))-f(x0-h(i)))./(2*h(i));
    err(i)=abs(f_approx-f_exact);
    d_error(i)=abs(((h(i)^2)*sin(x0))./6);    
end

plot(h,err,'o-');
figure; %opens a new plot window
loglog(h,err,'o-');

The loglog plot loooks decent enough, The problem you are running into (I think) is a loss of accuracy due to cancellation (i.e. when you substract two numbers that are very close).

enter image description here

$\endgroup$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .