Filter löschen
Filter löschen

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

14 Ansichten (letzte 30 Tage)
Tb
Tb am 29 Okt. 2020
Kommentiert: Tb am 29 Okt. 2020
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.

Akzeptierte Antwort

Ameer Hamza
Ameer Hamza am 29 Okt. 2020
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 Kommentare
Tb
Tb am 29 Okt. 2020
Ah ok, my bad, yes it does solve the issue, thanks.
Tb
Tb am 29 Okt. 2020
Also, thank you John for the explanation

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by