Approximating derivative and plotting error.
Afficher commentaires plus anciens
Hi, I'd sincerely appreciate it if someone were willing to review the few lines of code below and indicate why they don't quite yield the expected output.
I am asked to generate using MATLAB approximated values of f(x)=cos(x) at nodes x+h,x-h with random errors <=5*10^-6 (using rand ) for h=10^-8,10^-7,...,10^-1. Hence, f_approx(x+h)=f(x+h)+e(x+h) f_approx(x-h)=f(x-h)+e(x-h) where e(x)<=5*10^-6 in order to then find approximation for f'(1.2) by using the approximation: f'(x)=[f(x+h)-f(x-h)]/2h I am finally asked to plot the error with respect to the value of h.
Below is my code. I am not really sure why it yields one line across the y axis and another across the x axis.
h=(10^-1).^[1:8];
x=1.2;
fminush=cos(x-h)+(5e-6)*rand(1,1);
fplush=cos(x+h)+(5e-6)*rand(1,1);
fder=(fplush-fminush)./(2*h);
plot(h,abs(-sin(x)-fder))
Réponses (1)
Shubham Mishra
le 21 Nov 2020
0 votes
max_iter=50;
x0=1;
tolx= 1e-3;
x=x0;
xold=x0;
for i= 1:max_iter
f= (1-x)*exp(-2*x)-3*exp(-x)+2;
df= -2*(1-x)*exp(-2*x)-exp(-2*x)+3*exp(-x);
x= x-f/df;
err(i)= abs(x-xold);
xold=x;
if err(i)<tolx
break;
end
end
for i=1:8
err(i)=err(i)*1000
end
plot(err(i),i,'--r');
Catégories
En savoir plus sur Language Fundamentals dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!