Approximating derivative and plotting error.

조회 수: 3 (최근 30일)
Yuval
Yuval 2013년 11월 7일
답변: Shubham Mishra 2020년 11월 21일
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))

답변 (1개)

Shubham Mishra
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');

카테고리

Help CenterFile Exchange에서 Interpolation에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by