Analysis of formulas derived from Taylor Series- Consider the function f(x) = x3
ID: 3712019 • Letter: A
Question
Analysis of formulas derived from Taylor Series-
Consider the function f(x) = x3 ? 2x + 4 on the
interval [? 2, 2] with h = 0.25 . Use the forward, backward, and centered finite difference
approximations for the first and second derivatives so as to graphically illustrate which
approximation is most accurate. Graph all three first derivative finite difference approximations
along with the analytical, and do the same for the second derivative as well.
You should write a Python program that does this, using pyplot to create plots with meaningful
title and labels.
To complete this task, you should embed within your report
? The two graphs
? The well-documented neatly formatted code for your program
Explanation / Answer
Solution:
code:
clc
clear all
close all
h=0.25;
x=[-2:h:2];
n=max(size(x));
for i=1:n
fi(i)=func(x(i));
fi_1(i)=func(x(i) - h);
fi_2(i)=func(x(i) - 2*h);
fiplus1(i)=func(x(i) + h);
fiplus2(i)=func(x(i) + 2*h);
f1st_theory(i)=3*x(i)^2 - x(i);
f1st_forw(i)=(fiplus1(i) - fi(i))/h;
f1st_back(i)=(fi(i) - fi_1(i))/h;
f1st_cent(i)=(fiplus1(i) - fi_1(i))/2/h;
f2nd_theory(i)=6*x(i);
f2nd_forw(i)=(fiplus2(i)-2*fiplus1(i) + fi(i))/h^2;
f2nd_back(i)=(fi(i) - 2*fi_1(i) + fi_2(i))/h^2;
f2nd_cent(i)=(fiplus1(i) - 2*fi(i) + fi_1(i))/h^2;
end
fprintf(' x fi fi-1 fi+1 fi-2 fi+2 ')
fprintf('f''_Exact f''_Back f''_Cent f''_Forw ')
for i=1:n
fprintf('%8.3f %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f '...
,x(i),fi(i),fi_1(i),fiplus1(i),fi_2(i),fiplus2(i),f1st_theory(i),...
f1st_back(i),f1st_cent(i),f1st_forw(i))
end
fprintf(' x fi fi-1 fi+1 fi-2 fi+2')
fprintf('f''''_Exact f''''_Back f''''_Cent f''''_Forw ')
for i=1:n
fprintf('%8.3f %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f '...
,x(i),fi(i),fi_1(i),fiplus1(i),fi_2(i),fiplus2(i),f2nd_theory(i),...
f2nd_back(i),f2nd_cent(i),f2nd_forw(i))
end
function [ f ] = func( x )
%Calculate f(x)=x^3-2x+4
f=x^3-2*x+4;
end
I hope this helps if you find any problem. Please comment below. Don't forget to give a thumbs up if you liked it. :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.