Effacer les filtres
Effacer les filtres

approximation with loop without using built in factorial function

1 vue (au cours des 30 derniers jours)
OLUBUKOLA ogunsola
OLUBUKOLA ogunsola le 4 Juin 2016
Commenté : Star Strider le 4 Juin 2016
I'm supposed to write a code to approximate the exp of a number with this formula e=sumation (1/k)= 1+1+1/2+1/6+1/24+.....( for k=0 to infinity) the only input id delta which is the difference between the approximation of e and the built in value. the function stops when the difference between e(approximated ) and built in e is not more than delta. i have the following code , but it give giving back to be the first approximated value of e and first value of k . i can't use the factorial built in function.
function [e,k]= approximate_e (delta)
format long
s=exp(1);
k=0;
sn=1;
fac=1;
while (sn-s)>=abs(delta);
fac=fac *(k+1);
sn=sn+(1/fac);
k=k+1;
end
e=sn;
end
please what I'm i doing wrong here ? thanks

Réponse acceptée

Star Strider
Star Strider le 4 Juin 2016
Modifié(e) : Star Strider le 4 Juin 2016
You need to add an abs call in your while condition:
abs(sn-s)
and your code works.
EDIT
This is actually a one-liner:
e = 1 + sum(1./cumprod(1:100));
  2 commentaires
OLUBUKOLA ogunsola
OLUBUKOLA ogunsola le 4 Juin 2016
hmmm, wrong placement of abs. thanks a lot . its amazing how fast people respond on this forum. can't wait for the time that ill be good enough to answer people's questions
Star Strider
Star Strider le 4 Juin 2016
My pleasure.
You’re probably good enough already to answer some of them. You learn a lot by just hanging out here, especially about what constitutes a ‘good’ Answer. Read the Questions with Accepted Answers to get an idea of what works best, stay within your areas of expertise (that will expand quickly as you learn more), feel free to experiment with new approaches, read the MATLAB documentation (you’d be surprised at how many people don’t), and don’t be discouraged if another Answer is Accepted. Efficient code is usually the best code. As with everything else in life, persistence pays off. You’ll eventually have the 3000 Reputation Points necessary to become Editor.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by