1

Hi there I’ve been working on trying to plot the convergence of 'e' through using the equation 1/N! with limits from 0 to 9.

clc,clear
terms=[1];
x=10;
for i=2:x
    terms(i,1)=terms(i-1,1) + 1/factorial(i);
end
disp(terms)
xplotrange = 0:9;
plot(xplotrange,terms,'b-')

With the code I intened to plot the number of terms in the 'x' axis and the result of the series in the 'y' axis. But I am confused as to why the array of numbers outputted in the for loop converges at 1.718 instead of 2.718?

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
KC ReLoDZz
  • 33
  • 4

2 Answers2

2

Initializing terms with 1 and starting your for loop at 2, you effectively start at i=1, but the sum has to start at i=0. 1/0! is the 1 you are missing.

Daniel
  • 36,610
  • 3
  • 36
  • 69
2

As @Daniel stated, Euler's number via Taylor expansion should start from x=0 . Thus you can adjust your code to something like below

terms=[1];
x=10;
for i=2:x
    terms(i,1)=terms(i-1,1) + 1/factorial(i-1);
end
disp(terms)
xplotrange = 0:9;
plot(xplotrange,terms,'b-')

or a method using cumsum, e.g.,

terms=[1];
x=10;
terms = cumsum(1./factorial(0:x));
disp(terms)
xplotrange = 0:x;
plot(xplotrange,terms,'b-');
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81