While loop troubles and errors with summation

13 visualizzazioni (ultimi 30 giorni)
Eathan
Eathan il 30 Mar 2014
Commentato: Image Analyst il 30 Mar 2014
Hi, I need help fixing my code for MATLAB. I'm trying to write a 'while' loop code for the geometric series. Just a brief background on goemetric series, is basically a summation of terms in which each term except the first one can be found by multiplying the previous term by 0.5. As you add up the terms, it should reach the limit close to 1.
i.e. 0+1/2 + 1/4 + 1/8 + 1/16 + 1/32......=1
My code is to find the sum of these terms so that the difference between 1 and the sum of these terms is less than 0.001 i.e.
1-sum<0.001.
here is my code:
a=0;
r=0.5;
n=1;
sum=0;
sum_diff=0;
while 1-sum<0.001;
sum=sum+(a*(1-r^n)/(1-r));
n=n+1;
sum_diff=sum_diff+(1-sum);
end;
fprintf('\n %1.4f\n %1.4f \n', sum,sum_diff)
The problem is that when I run the code, I only get 0.0000 for the 'sum' term. I know that is not right. Can someone help me with this code?

Risposte (2)

Jan
Jan il 30 Mar 2014
Your a is zero. Then a*(1-r^n)/(1-r) is zero also.
  1 Commento
Eathan
Eathan il 30 Mar 2014
Well I changed a=1, i still get 0.0000. Is there something else wrong with it? thank you for answering earlier.

Accedi per commentare.


Image Analyst
Image Analyst il 30 Mar 2014
sum is zero so
while 1-sum<0.001
is really
while 1 < 0.001
so you never enter the while loop, and sum remains zero no matter what a is.
DON'T USE SUM AS THE NAME OF A VARIABLE. sum is a built in function and you overwrote it - a very very bad idea.
  1 Commento
Image Analyst
Image Analyst il 30 Mar 2014
By the way, please view this so you can learn exactly what I did to solve your problem: http://blogs.mathworks.com/videos/2012/07/03/debugging-in-matlab/ and you can solve these things yourself next time. It will be much faster for you than waiting hours for me to answer your post.

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by