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

2 Ansichten (letzte 30 Tage)
Mark Dillon
Mark Dillon am 23 Jul. 2015
Beantwortet: Star Strider am 23 Jul. 2015
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.

Akzeptierte Antwort

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

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by