It is necessary with the help of Matlab to approximate the series:

y(n)=(1/0!) + (1/1!)+..+(1/n!) 

And you need to find n for which y will be equal to exp (1). I wrote the following code to solve this problem:

 for n=1:100 while y>exp(1) y=(1/(factorial(n-1))) y=y+(1/(factorial(n))) disp(n) end end 

But n not reflected and after trying the variants of this code it is impossible to find n . Tell me how to solve the problem?

  • while y>exp(1) I think you wrote something wrong with that. The partial sum of a row is always under the limit. And y= ... y=y+ you surely did not make a mistake? I think the assignment here is too much. I have never written a matlab but I would have made while ( exp(1) - y > 1e-10) y = y + (1/(factorial(n)) . By the way, the answer is when - never! - pavel
  • @pavel Theoretically never, but since the work goes with limited accuracy (64 bits), then pretty soon: with n = 17. - user176149

1 answer 1

No need to cycle for. There is one condition: y <exp (1), the while loop works on it. Inside the loop, add 1 / factorial (n) and increase the value of n.

 n = 0; y = 0; while y < exp(1) y = y + 1/factorial(n); n = n + 1; end disp(n - 1) 

Answer: 17. (At the end, one is subtracted because it was added in the last pass of the cycle.)

It must be borne in mind that the partial sum of this series will in fact never be equal to the number e. Equality is achieved only due to rounding caused by the finite precision of the representation of numbers in Matlab.