How do I run an infinite series by creating a function?

1 view (last 30 days)
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:
And I need to calculate and then stop within 1e-7.

Accepted Answer

Star Strider
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’.)

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!