Reputation: 2457
I'm trying to compare integers in a while
loop, shown below:
Sigma_Wanted_Start = 0.000;
Sigma_Wanted_End = 0.009;
Sigma_Increment = 0.001;
Sigma_Current = 0.000;
while (Sigma_Wanted_End ~= Sigma_Current)
Sigma_Current = Sigma_Current + Sigma_Increment;
end
If Sigma_Wanted_End == 0.009
, then we would stop the for loop. The problem is that the statement is shown true
even if Sigma_Wanted_End == Sigma_Current
.
Another strange thing is that if Sigma_Wanted_End == 0.008
, then the while loop would stop.
I thought it's the difference between integers, and double
, so I used double
on all the numbers, but the problem still occurred.
Does anybody know why?
Thanks in advance
Upvotes: 0
Views: 118
Reputation: 1453
floating point representations in matlab are not equal because of rounding problems.
let say if we have
x = 0.3
0.4-0.1
x==y
this will give you false so you could do this
Sigma_Wanted_Start = 0.000;
Sigma_Wanted_End = 0.009;
Sigma_Increment = 0.001;
Sigma_Current = 0.000;
while (~((Sigma_Wanted_End - Sigma_Current)<0.0))
Sigma_Current = Sigma_Current + Sigma_Increment;
end
Upvotes: 1
Reputation: 212959
You should not test for exact equality when comparing floating point values, due to the finite precision available. Instead do something like this:
while (Sigma_Current < Sigma_Wanted_End)
Sigma_Current = Sigma_Current + Sigma_Increment;
end
Upvotes: 2