Taylor polynomial maximum error.
3 views (last 30 days)
Show older comments
hello, I was given this code that evaluates several Taylor polynomials and their errors for increasing degrees. The particular function being approximated is exp(x) on [-b,b].
% TITLE: Evaluate Taylor polynomials for exp(x) about x = 0
%
% This evaluates several Taylor polynomials and their errors
% for increasing degrees. The particular function being
% approximated is exp(x) on [-b,b].
% Initialize
clc,clear all, close all
b = input('Give the number b defining the interval [-b,b], b= ');
if isempty(b)
b
disp('b is not defined')
break
end
h = b/10;
x = -b:h:b;
max_deg = 4;
% Produce the Taylor coefficients for the function exp(x) when
% expanded about the point a = 0. The coefficients are stored
% in the array c, which will have length max_deg+1.
c = ones(max_deg+1,1);
fact = 1;
for I = 1:max_deg
fact = I*fact;
c(I+1) = 1/fact;
end
x
c
% Calculate the Taylor polynomial
p1 = polyeval(x,0,c,1);
p2 = polyeval(x,0,c,2);
p3 = polyeval(x,0,c,3);
p4 = polyeval(x,0,c,4);
% Calculate the errors in the Taylor polynomials
true= exp(x);
err1 = true-p1;
err2 = true-p2;
err3 = true-p3;
err4 = true-p4;
% Print the errors in tabular format
diary exp_taylor.txt
disp(' x exp(x) err1 err2 err3 err4')
for I = 1:length(x)
fprintf('%7.3f%10.3f%14.3e%14.3e%14.3e%14.3e\n', ...
x(I),true(I),err1(I),err2(I),err3(I),err4(I))
end
diary off
figure(1)
plot(x,err1,x,err2,x,err3,x,err4)
legend('e^x-p_{1}(x)','e^x-p_{2}(x)','e^x-p_{3}(x)','e^x-p_{4}(x)',...
'Location','Best')
figure(2)
plot(x,err1,'k-',x,err2,'k--',x,err3,'k:',x,err4,'k-.')
legend('e^x-p_{1}(x)','e^x-p_{2}(x)','e^x-p_{3}(x)','e^x-p_{4}(x)',...
'Location','Best')
and polyeval is given as
function value= polyeval(x,alpha,coeff,n)
%
%function value= polyeval(x,alpha,coeff,n)
%
% Evaluate a Taylor polynomial at the points given in x, with
% alpha the point of expansion of the Taylor polynomial, and
% with n the degree of the polynomial. The coefficients are to
%be given in coeff; and it is assumed there are n+1 entries in
% coeff with coeff(1) the constant term in the polynomial
value= coeff(n+1)*ones(size(x));
z = x-alpha;
for I = n:-1:1
value = coeff(I) + z.*value;
end
end
Then, I was asked to modify the script to evaluate the maximum error for different values of x and the degree of the polynomials n (n=1,2,3,4) by using this formula
I would really appreciate it if you could give me some tips on how to start edting the scrpit to get the maximum error.
Thank you in advance.
0 Comments
Answers (0)
See Also
Categories
Find more on Polynomials in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!