Matlab Script Accuracy of Results
3 次查看(过去 30 天)
显示 更早的评论
I'm trying to write a Matlab script that shows the order of accuracy of the forward and central differencing methods for the first derivative of f = exp (x) at x = 0. The graph attached is the result I'm looking for.
Here is what I have so far in forward differencing method but I'm kinda stuck. Can you show me where I made my mistakes.
clear all
close all
delx = 1;
x = 0;
y = exp(x);
fig = figure();
set(fig,'color','white')
plot(x,y,'LineWidth',2)
xlabel('x')
ylabel('y')
grid on
yderiv = exp(x);
fig = figure();
set(fig,'color','white')
plot(x,yderiv,'LineWidth',2)
xlabel('x')
ylabel('y')
grid on
%%%Forward Differencing
yderivest = (y(2:end) - y(1:end-1))./delx;
hold on
plot(x(2:end)-delx/2,yderivest,'r-','LineWidth',2)
0 个评论
采纳的回答
John D'Errico
2017-10-19
You made a LOT of mistakes.
delx = 1;
x = 0;
y = exp(x);
So you set x to zero. Then you evaluated exp(x).
That does NOT create a function of x. It simply evaluates exp(x), thus, here exp(0).
And I'm not sure what you think you are doing here:
yderivest = (y(2:end) - y(1:end-1))./delx;
y is a scalar variable. It is not a vector as you built it.
I'll give you a couple of suggestions to get you started.
Generate a vector of h values. Something like this:
h = 2.^(-20:1:0);
And you might create a function.
testfun = @(x) exp(x);
Now your code will work for other functions, doing not much more than changing testfun.
So what would this do?
x0 = 0;
fdiff = (testfun(x0 + h) - testfun(x0))./h
How would you change that for a central difference?
What is the error in the derivative approximation? Well, you know that the correct derivative is just:
truederiv = exp(x0);
fdifferr = abs(truederiv - fdiff);
Now you can plot the result as a function of h. Plot will work, but perhaps loglog will be a better choice of plotting tool. Think about why that might be true. What does the slope of such a resulting error plot mean when you plot it using loglog axes?
更多回答(0 个)
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!