Approximating derivative and plotting error.
3 ビュー (過去 30 日間)
古いコメントを表示
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))
0 件のコメント
回答 (1 件)
Shubham Mishra
2020 年 11 月 21 日
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');
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!