Plotting the exp(-x) using the power series expansion and for loop

Hello,
I am trying to program the function exp(-x) using the power series and for loop and plotting it against the actual exp(-x) to check what the error is, however, for some reason the program does not show the correct graph for the power series expansion. My code is below:
x1 = 0:0.1:5;
y = exp(-x1);
figure
plot(x,y,'k') % plots the true function e^-x in black
hold on;
ex1 = ones(1,51);
ex2= 0;
for n = 1:5
ex1 = ex1 + ((-ex1).^n).*((x1.^n)/(factorial(n)))
end
plot(x1,ex1,'r');
The issue is with the expression for ex1, but I can't figure out why it isn't working as I am sure that I have used the correct formulae. Thanks.

 Accepted Answer

The series expansion is wrong. Check the following code
x1 = 0:0.1:5;
y = exp(-x1);
figure
plot(x1,y,'k') % plots the true function e^-x in black
hold on;
ex1 = zeros(size(x1));
for n = 0:5
ex1 = ex1 + (-1).^n.*(x1.^n)/(factorial(n));
end
plot(x1,ex1,'r');

6 Comments

This code gives exactly the same graph as a I was getting before
As in the same incorrect graph.
No. Actually, it does not give the same result as the code you posted. The two are VERY distinct.
The code he wrote is correct, and the code in your question is completely different.
The actual 6 term truncated Taylor polynomial is what is created in the loop, as written by Ameer.
syms x
exp6 = taylor(exp(-x),x,'order',6)
exp6 = 
x5120+x424x36+x22x+1
oops. sorry for the poor formatting...
- x^5/120 + x^4/24 - x^3/6 + x^2/2 - x + 1
I'll plot the two, but go only out as far as x == 3, since the two diverge quite strongly beyond that point.
fplot(exp(-x),[0,3],'b--')
hold on
fplot(exp6,[0,3],'r-')
legend('exp(-x)','6 term truncated Taylor approximation')
When you plot all the way out to x == 5, the approximation has diverged so badly, that the function exp(x) virtually disappears due to the axis scaling.
@Hummd Ghouri, If you want a better approximation, then you will need to increase the order of the polynomial
x1 = 0:0.1:5;
y = exp(-x1);
figure
plot(x1,y,'k') % plots the true function e^-x in black
hold on;
ex1 = zeros(size(x1));
for n = 0:20
ex1 = ex1 + (-1).^n.*(x1.^n)/(factorial(n));
end
plot(x1,ex1,'r');
Ah ok, my bad, yes it does solve the issue, thanks.
Also, thank you John for the explanation

Sign in to comment.

More Answers (0)

Categories

Find more on Fourier Analysis and Filtering in Help Center and File Exchange

Asked:

Tb
on 29 Oct 2020

Commented:

Tb
on 29 Oct 2020

Community Treasure Hunt

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

Start Hunting!