Equality between 2 floats not recognized when using <= relational operator
2 views (last 30 days)
Hi everyone. I have an if/else loop nested in a for-loop, which will run if Money_types(ii) <= Var2
Money_types(ii) is a vector's elements that will be indexed according to the for-loop, and Amount_to_Return is the difference of 2 other variables calculated earlier in the code.
for ii = 1:14
if Money_types(ii) <= Var2
The problem is, matlab is not recognizing equality between 2 floating points.
- So if Money_types(ii)=0.02 and Var2=0.05, then it recognizes that Money_types(ii) <= Var2 because 0.02 is < 0.05, and hence the if/else loop runs.
- However, if Money_types(ii) =0.05 and Var2=0.05, then it does not recognize that Money_types(ii) <= Var2, even though 0.05 = 0.05, hence the if/else loop doesn't run and skips to the next indexed element in the Money_types vector.
I searched it up and apparenty it's to do with matlab not storing floats very accurately, but does anyone know how I can fix / get around this problem? How do I write code where matlab recognizes if Money_types(ii) <= Var2 (if they are equal), so that the if/else loop can run?
Any help is really appreciated, thanks!
Steven Lord on 22 Sep 2022
I searched it up and apparenty it's to do with matlab not storing floats very accurately,
No, that is not the cause.
Are the numbers just displayed as equal or are they actually equal?
x1 = 1 + 1e-6
x2 = 1 + 1e-8
Using the default display format x1 and x2 appear equal. But by inspection of how they were created they obviously aren't actually (down to the last bit) equal, which the == operator shows.
x1 == x2 % false is the correct answer
To show that x1 and x2 are not actually equal you can look at the difference between the two numbers or you can try changing the display format.
difference = x1 - x2 % Not 0
If you want to detect when x1 and x2 are "close enough" you can check if the difference between the two numbers is "small enough" (for some definition of "small enough".) The ismembertol function may also be of interest.
areTheyCloseEnough = abs(x1-x2) <= 1e-5 % 1e-5 is this line's definition of "small enough"
As an analogy, in real life if you know the first say 50 digits of π do you know the full and actual value of that transcendental number? No. Is knowing the first 50 digits of π good enough for most purposes? Since "thirty-nine digits are sufficient to perform most cosmological calculations, because that is the accuracy necessary to calculate the circumference of the observable universe with a precision of one atom." [emphasis added] I'd say yes.