While loop not terminating when condition is met?
8 次查看(过去 30 天)
显示 更早的评论
% 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
2019-2-21
编辑:per isakson
2019-2-21
If you want help, ignoring comments is not a good tactic.
fprintf( 1,'>>> %bx\n %bx\n', W0, W0g );
回答(1 个)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!