How do I run an infinite series by creating a function?
4 views (last 30 days)
Show older comments
I am working on a homework problem and cannot seen to get it started properly. So far I have a function created,
if true
% function [e]=Euler(x,n)
e=1/factorial(x);
for k=0:n
e=e+(1/factorial(k));
end
end
end
I just seem to have hit a wall now and cannot get passed it. I am trying to use the infinite series for Euler's number:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/147344/image.gif)
And I need to calculate and then stop within 1e-7.
0 Comments
Accepted Answer
Star Strider
on 23 Jul 2015
You’re missing a test for convergence. I don’t understand your needing any arguments for your function, since it never uses them. It calculates the series and is entirely self-contained. I would just set ‘n’ arbitrarily high and break out of the loop when it converged.
n = 150;
e=0;
ep = 0; % Previous Value Of ‘e’
for k=0:n
e=e+(1/factorial(k));
if e-ep < 1E-7 % Test For Convergence
break
end
de = e;
end
When I ran it, it required only 11 iterations to converge. (I would use a while loop, but your code works with a high enough value for ‘n’.)
0 Comments
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!