MATLAB Answers

Taylor Series of e^x

140 views (last 30 days)
The program calculates e^x by adding terms of the series and stopping when the absolute value of the term that was added last is smaller than 0.0001. Use a while-end loop, but limit the number of passes to 30. If in the 30th pass the value of the term that is added is not smaller than 0.0001, the program stops and displays a message that more than 30 terms are needed.
clear
clc
fprintf('Solving e^x using Taylor Series\n');
x=input('x = ');
n=30;
i=0;
f=1;
while i<n || i==n
f=f+(x.^i)/factorial(i);
i=i+1;
end
y=f-1
This is where I am stuck, I don't know how to limit the n to 30 and how can I make a condition that if the value of the term is smaller than 0.0001 it will stop.
Any help would be appreciated, Thank you!

  1 Comment

Walter Roberson
Walter Roberson on 21 Mar 2020
while term is in range && iterations is in range
Calculate a term
accumulate term into total
increment iterations

Sign in to comment.

Accepted Answer

Subhamoy Saha
Subhamoy Saha on 21 Mar 2020
clear
clc
fprintf('Solving e^x using Taylor Series\n');
x=input('x = ');
n=30;
i=0;
f=1;
while i<=n
last_term=(x.^i)/factorial(i);
if (x.^i)/factorial(i)<0.0001
msgbox('Last term is smaller than 0.0001 and hence stopped')
break
elseif i==n && last_term>0.0001
msgbox('More steps needed')
break
end
f=f+last_term;
i=i+1;
end
y=f-1

  4 Comments

Show 1 older comment
Walter Roberson
Walter Roberson on 22 Mar 2020
We recommend against providing complete solutions to homework questions.
Subhamoy Saha
Subhamoy Saha on 25 Mar 2020
I didn't realised that @Walter.
Joseph Melo Manalo
Joseph Melo Manalo on 25 Mar 2020
I just read the rules in asking homework and I am really sorry for not tagging "homework". I thank you both also for answering my questions. I have learn that I can learn better using actual example, so even though Subhamoy Saha didn't exactly write the code that I need. I can work from there. Again I am sorry and Thank you both!

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!