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

4 次查看(过去 30 天)
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.

采纳的回答

Star Strider
Star Strider 2015-7-23
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 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by