While loop troubles and errors with summation

조회 수: 12 (최근 30일)
Eathan
Eathan 2014년 3월 30일
댓글: Image Analyst 2014년 3월 30일
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?
  댓글 수: 1
Jan
Jan 2014년 3월 30일
I've formatted your code to make it readable.

댓글을 달려면 로그인하십시오.

답변 (2개)

Jan
Jan 2014년 3월 30일
Your a is zero. Then a*(1-r^n)/(1-r) is zero also.
  댓글 수: 1
Eathan
Eathan 2014년 3월 30일
Well I changed a=1, i still get 0.0000. Is there something else wrong with it? thank you for answering earlier.

댓글을 달려면 로그인하십시오.


Image Analyst
Image Analyst 2014년 3월 30일
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
Image Analyst
Image Analyst 2014년 3월 30일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by