While loop not terminating when condition is met?

7 vues (au cours des 30 derniers jours)
Nick Nuzzo
Nick Nuzzo le 21 Fév 2019
Modifié(e) : Nick Nuzzo le 22 Fév 2019
% 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 commentaires
per isakson
per isakson le 21 Fév 2019
Modifié(e) : per isakson le 21 Fév 2019
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 le 22 Fév 2019
Modifié(e) : Nick Nuzzo le 22 Fév 2019
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.

Connectez-vous pour commenter.

Réponses (1)

Walter Roberson
Walter Roberson le 21 Fév 2019
Modifié(e) : Walter Roberson le 21 Fév 2019
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.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by