While loop not terminating when condition is met?

조회 수: 7 (최근 30일)
Nick Nuzzo
Nick Nuzzo 2019년 2월 21일
편집: Nick Nuzzo 2019년 2월 22일
% This is a part of my code where all these variables that aren't defined here have
% been previously defined. W0g is a constant value and R is varied which changes W0
R = 1;
while 1
We_W0 = (a1+(b*W0g^C_1*AR^C_2*x_W0^C_3*W0_S^C_4*max^C_5))*Kvs
if(type == 1)
W3_W2 = exp((-R*SCF)/((V*(L_Dc))));
else
W3_W2 = exp(-(R*SCFpower)/((np*(L_Dc))));
end
Wf3 = W2_W1*W1_W0*W0g*(1-W3_W2);
Wf4 = W3_W2*W2_W1*W1_W0*W0g*(1-W4_W3);
Wf5 = W4_W3*W3_W2*W2_W1*W1_W0*W0g*(1-W5_W4);
Wftot = Wf1+Wf2+Wf3+Wf4+Wf5;
Wf = 1.06*Wftot;
W0 = (Wc+Wp+Wpd+Wf)/(1-We_W0);
if W0 == W0g
disp('Required range is');
disp(R);
break;
else R = R + 1;
end
end
The problem I'm having is that this condition is met. When I output the variable W0 there is a point where it is equal to W0g. Why is the while loop not stopping when this condition is met?
Thanks
  댓글 수: 3
per isakson
per isakson 2019년 2월 21일
편집: per isakson 2019년 2월 21일
If you want help, ignoring comments is not a good tactic.
See Why is 0.3 - 0.2 - 0.1 (or similar) not equal to zero? and add this line above if W0 == W0g
fprintf( 1,'>>> %bx\n %bx\n', W0, W0g );
Nick Nuzzo
Nick Nuzzo 2019년 2월 22일
편집: Nick Nuzzo 2019년 2월 22일
Thank you per isakson. I just ended up breaking the loop when the value of the ratio of W0 and W0g was very close to 1.

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

답변 (1개)

Walter Roberson
Walter Roberson 2019년 2월 21일
편집: Walter Roberson 2019년 2월 21일
The only time you should ever compare for floating point equality is a situation where one of the numbers has been extracted from an array , and the array members are being compared. For example it is okay to compare xx(kk) to min(xx) because min will return a bit for bit identical copy of a value from the array .
There are also some cases you can count on involving multiplication and division by 2 or 4. (xx/2)*2== xx will be true for floating point xx not nan and not between eps(realmin) and realmin
But otherwise never compare a calculated value for equality. (xx/3)*3 ==xx is not always true.

카테고리

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

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by