While loop troubles and errors with summation

13 次查看(过去 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?

回答(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