I'm not sure how to relate a counter
Mostrar comentarios más antiguos
I have a equation:
∞
𝑒 = ∑ 𝑛!
n = 0
I need to some how relate the counter, which starts at 1, with the factorial n that starts at 0. But I'm not sure how to go about this.
I need to make j=1 when n=0 and so on j=1,2,3,4,5,6... when n=0,1,2,3,4.....
i have to do this via for loops to get the first 10 terms of the sequence as well as calulating the series then plotting it.
I'm not sure how to relate the counters, how to make j=1 when n=0 and so on.
Respuestas (1)
Riccardo Scorretti
el 7 de Abr. de 2022
Editada: Riccardo Scorretti
el 7 de Abr. de 2022
Hi Saskiaa, if the question is just "how to have j = 1, 2, 3 ... when n = 0, 1, 2 ..." it is enough to write the loop with respect of one of the two variables (namely n) and then compute the other, for instance:
for n = 0 : 9
j = n + 1;
% some other computation
end
However, I guess that in your particualr example the problem is that 0! = 1! = 1. You could handle separately the case n=0 by rewriting the sum like:

This gives something like:
value = 1.0;
fact = 1.0;
for n = 1 : 10
fact = fact * n;
value = value + 1/fact;
end
fprintf('sum = %20.15f (reference = %20.15f)\n', value, exp(1));
Notice that this kind of code is for pedagogical purpose only. In "true" Matlab coding, I would rather vectorize like that:
fact = cumprod(1:10);
value = 1.0 + sum(1./fact);
fprintf('sum = %20.15f (reference = %20.15f)\n', value, exp(1));
4 comentarios
Saskiaa Vamadevan
el 7 de Abr. de 2022
Let's see that (by the way, it would be better if you format your code... as a code).
The problem is fundamentally that your loop has to start from 0, not to 1. By starting the loop from 1, you are missing the term 1/0! = 1/1 = 1, which explains why you get a value close to 1.7 instead of 2.7. By doing this, if you want to limit to n = 10, the size of sumtoplot must be 11 (= 10+1), and when you access to if in the first loop, you must use sumtoplot(n+1):
clear
sv=0;
sumtoplot = zeros(1,10+1);
for n = 0:10 % Set up a FOR loop for counter n % ***
term = 1 / factorial(n);
disp(term)
sv = sv + term;
sumtoplot(n+1) = sv; % ***
end
disp('This is the sum of the series')
disp(sv)
% Calculate the error of the series
errorseries = (sv-exp(1))*100/exp(1);
disp('This is the error in %')
disp(errorseries)
% Create a plot of the series based on the number of terms in the
% sequence
ordersequence = 1:11; % ***
plot(ordersequence,sumtoplot,'b-x')
hold on
% Where the series should converge
plot([1,10],[exp(1),exp(1)],'k-')
hold off
% Customise the plot
xlabel('Number of terms in the series')
ylabel('Value of the series')
legend('1/n!','e')
Saskiaa Vamadevan
el 7 de Abr. de 2022
Riccardo Scorretti
el 7 de Abr. de 2022
You are welcome.
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
