Forward and central difference help - loglog plot of errors vs h

6 ビュー (過去 30 日間)
Savannah Phillips
Savannah Phillips 2020 年 3 月 17 日
回答済み: Pankaj Narayan Sawant 2021 年 9 月 9 日
Hi! If anyone is able, I'd really appreciate help on this coursework I'm stuck on. The question is
Within your file, test your difference quotient formulas with h = 10^(−i) for i = 1, 2, . . . , 10. Plot the errors versus h in a figure with double-log axes. Can you observe the expected rate of convergence (asymptotic behaviour as h → 0)? What happens for very small h?
My code is this
f = @(x) sin(x); %function handle
for i = 1:10
h = 10.^(-i);
end
[fd,cd] = FDCD(f, 0.9, 10.^(-i));
% f'(0) = 1 for this question
errors = 1 - fd; % Approximation error for forward difference quotient
% Setting the figure
figure
loglog(errors, h);
% Formatting the plot
(just title, axes labels, etc)
When I run the code, the graph appears, formatted etc, but there's no points/lines. I'm not sure what I need to do. I'm fairly certain my function [fd,cd] (a function for forward and central difference quotient) is correct. I've got it on another tab and it's just
function [fd,cd] = FDCD(f,x,h)
% forward-difference quotient
fd = (f(x + h) - f(x))/h;
% central-difference quotient
cd = (f(x + h) - f(x - h))/2.*h;
If anyone can spot what I'm doing wrong, I'd really appreciate it. Thank you :-)

採用された回答

Sriram Tadavarty
Sriram Tadavarty 2020 年 3 月 17 日
編集済み: Sriram Tadavarty 2020 年 3 月 17 日
Hi Savvanah,
In the for loop, h is over written with the last value. I feel that is the issue in the code. Update with h(i) instead of h in the for loop. And then call the FDCD function in the for loop. Here is the code that does the modifications mentioned
for i = 1:10
h(i) = 10.^(-i);
[fd(i),cd] = FDCD(f,0.9,h(i));
end
Hope this helps.
Regards,
Sriram
  3 件のコメント
Sriram Tadavarty
Sriram Tadavarty 2020 年 3 月 17 日
Hi Savannah, I made modification to the answer. Please look at it and let me know, if the same is expected.
Savannah Phillips
Savannah Phillips 2020 年 3 月 17 日
Ah, ok thank you. that works now! Thank you again :-)

サインインしてコメントする。

その他の回答 (1 件)

Pankaj Narayan Sawant
Pankaj Narayan Sawant 2021 年 9 月 9 日
Consider the function u(x) = e3x. Write Matlab/Python/Julia code to compute the

カテゴリ

Help Center および File ExchangeGraphics Performance についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by