Taylor series for e^x with loop
Show older comments

How would I solve this problem and only compute the first 12 interations?
6 Comments
Steven Lord
on 18 Jul 2022
This sounds like a homework assignment. If it is, show us the code you've written to try to solve the problem and ask a specific question about where you're having difficulty and we may be able to provide some guidance.
If you aren't sure where to start because you're not familiar with how to write MATLAB code, I suggest you start with the free MATLAB Onramp tutorial to quickly learn the essentials of MATLAB.
If you aren't sure where to start because you're not familiar with the mathematics you'll need to solve the problem, I recommend asking your professor and/or teaching assistant for help.
Allison
on 18 Jul 2022
Edited: John D'Errico
on 18 Jul 2022
John D'Errico
on 18 Jul 2022
Lacking any code shown before, there was no evidence that you had done anything, on clear homework. But now you have shown at least some effort.
Note that I edited your code to make it readable. You might want to learn to do that, using the buttons on top of the edit window in Answers.
My questions would be:
1. What do you think this
index=1:n;
line does?
Does it serve any purpose, since index is never used?
2. Is n ever changing? How about the variable i? So will your loop ever terminate?
3. Since you will be generating a loop that explicitly goes for ALWAYS exactly 12 iterations, would a for loop be a better choice than a while loop?
4. What does this line do, since that is not the general series for exp(x)?
ex= 1+x+((x)^i/factorial(i));
(Yes, it is sort of related, in the sense that the first two terms are correct, and the third term there you have written is a form for the general term in the sum. But that does not make it the correct sum.)
5. What are you doing with the variable ex? Did not the series involve a sum, in this case of 12 total terms?
6. Is the fprintf syntax correct? Did you read the help for fprintf? Why not? Look at the examples shown in the docs for fprintf.
Why not take another shot at it, based on the comments I've made here.
Allison
on 19 Jul 2022
Works, I guess.
%x = input('Enter value of x');
x = 2;
value=0;
for i=0:12
value = value + x^i/factorial(i);
end
fprintf('Computed Value: %f', value)
value
exp(2)
Answers (1)
%% This is more efficient
x = 2;
v = 1;
n = 1;
d = 1;
for i = 1:20
n = n*x;
d = d*i;
v = v + n/d;
end
fprintf('Computed Value: %f', v)
1 Comment
x = 2;
v = 1;
s = 1;
for i = 1:20
s = s * x/i;
v = v + s;
end
fprintf('Computed Value: %f', v)
Categories
Find more on Programming 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!