0% found this document useful (0 votes)
11 views3 pages

Lab 06

The document presents a MATLAB script that calculates and compares numerical derivatives of the function exp(-x)*sin(3*x) using central, forward, and backward difference methods. It plots both the numerical derivatives and the exact derivative for visual comparison, as well as the errors associated with each numerical method. The results are displayed in two figures, one for the derivatives and another for the errors.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views3 pages

Lab 06

The document presents a MATLAB script that calculates and compares numerical derivatives of the function exp(-x)*sin(3*x) using central, forward, and backward difference methods. It plots both the numerical derivatives and the exact derivative for visual comparison, as well as the errors associated with each numerical method. The results are displayed in two figures, one for the derivatives and another for the errors.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

%Task

clc;
clear all;
close all;

Fun = @(x) exp(-x).*sin(3*x);


dFun = @(x) -exp(-x).*sin(3*x) + 3*exp(-x).*cos(3*x);

x = linspace(0, 4, 101);
h = x(2)-x(1);
F = Fun(x);

xCentral = x(2:end-1);
dFCentral = (F(3:end) -F(1:end-2))/(2*h);

xForward = x(1:end-1);
dFForward = (F(2:end) - F(1:end-1))/h;

xBackward = x(2:end);
dFBackward = (F(2:end) - F(1:end-1))/h;

dFExactCentral = dFun(xCentral);
dFExactForward = dFun(xForward);
dFExactBackward = dFun(xBackward);

errorCentral = abs(dFExactCentral - dFCentral);


errorForward = abs(dFExactForward - dFForward);
errorBackward = abs(dFExactBackward - dFBackward);

plot(x, dFun(x), 'k', 'LineWidth', 1.5);


hold on;
plot(xCentral, dFCentral, 'r', 'LineWidth', 1.2);
plot(xForward, dFForward, 'g', 'LineWidth', 1.2);
plot(xBackward, dFBackward, 'b', 'LineWidth', 1.2);
legend('Analytic', 'Central', 'Forward', 'Backward');
xlabel('x');
ylabel('Derivative');
title('Comparison of Numerical Derivatives');
grid on;

1
%Plot of errors:
figure;
plot(xCentral, errorCentral, 'r', 'LineWidth', 1.2);
hold on;
plot(xForward, errorForward, 'g', 'LineWidth', 1.2);
plot(xBackward, errorBackward, 'b', 'LineWidth', 1.2);

legend('Central error', 'Forward error', 'Backward error');


xlabel('x');
ylabel('Error');

title('Error in numerial derivative approximations');


grid on;

2
3

You might also like