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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by