필터 지우기
필터 지우기

How can I avoid infinite while loop?

조회 수: 3 (최근 30일)
Shashanka
Shashanka 2014년 7월 11일
댓글: Shashanka 2014년 7월 11일
N = 1; while (N<11) n = ((N*2)+(N+1))/N; N = n end
I wish to assign the value of 'n' to 'N' and compare if it's less than '11' and again enter the loop until 'N' is equal to 11. Please help.

채택된 답변

dpb
dpb 2014년 7월 11일
Well, since
((N*2)+(N+1))/N = (2*N+N+1)/N = (3*N+1)/N
n=3+1/N
and the expression approaches 3+ as a limit, never approaching anything near 11, the answer to the question posed is "you can't".
Need a different problem statement; perhaps you're looking for the point at which the change is less than some epsilon or something of that nature?
I'll wait for clarification of the actual problem nature before guessing further...
  댓글 수: 1
Shashanka
Shashanka 2014년 7월 11일
Thank you for the response! The example was a simplified version of the code I'm trying to run, which has decimal inputs. I have attached an image of the actual code below for your reference. The 'AxIFN' is to be updated with the latest value of 'AxIFN1' which is calculated with each iteration. Finally giving a value of 'AxIFN' which is less than '0.4'.
Thank you!

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

추가 답변 (2개)

Daniel
Daniel 2014년 7월 11일
Set a number equal to the number of times you want to loop (this case I chose 11), subtract each time you're in the loop, and add an and condition
LOOP_LIMIT = 11;
N = 1;
while (N < 11 && LOOP_LIMIT > 0)
n = ((N*2)+(N+1))/N;
N = n;
LOOP_LIMIT = LOOP_LIMIT-1;
end
  댓글 수: 1
Shashanka
Shashanka 2014년 7월 11일
Thank you for the response! The example was a simplified version of the code I'm trying to run, which has decimal inputs. I have attached an image of the actual code below for your reference. The 'AxIFN' is to be updated with the latest value of 'AxIFN1' which is calculated with each iteration. Finally giving a value of 'AxIFN' which is less than '0.4'.
Thank you!

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


C.J. Harris
C.J. Harris 2014년 7월 11일
편집: C.J. Harris 2014년 7월 11일
You have an infinity loop because your seed (N) is starting at one. Note that your equation ((N*2)+(N+1))/N is in fact equal to 3+(1/N), thereby meaning you'll only get 11 (or greater) for values less than 0.125.
Not sure why you even need a loop, can't you just rearrange, therefore getting n = 1/(11-3) = 0.125.
  댓글 수: 1
Shashanka
Shashanka 2014년 7월 11일
Thank you for the response! The example was a simplified version of the code I'm trying to run, which has decimal inputs. I have attached an image of the actual code below for your reference. The 'AxIFN' is to be updated with the latest value of 'AxIFN1' which is calculated with each iteration. Finally giving a value of 'AxIFN' which is less than '0.4'.
Thank you!

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

카테고리

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