Logical indexing of table failing
3 views (last 30 days)
Show older comments
I have a table with a field called gProb. I'm trying to run the following logical indexing:
T.gProb == 0.35;
However the logical indexing returns no hits when I know for certain that gProb does equal 0.35 in a few rows.
I've tried using other indexing conditions for gProb and they all work except this magic number for some reason.
I'm sure there must be a simple explanation for this, but at the moment cannot see why.
0 Comments
Answers (1)
John D'Errico
on 10 Apr 2021
No. You do NOT know it contains 0.35. In fact, MATLAB cannot represent 0.35 exactly in floating point arithmetic. This is for the same reason you cannot represent the fraction 1/3 as a finite decimal number.
So what you have there is APPROXIMATELY 0.35, created in that table in some way that we don't know. And then you are comparing that number to this:
sprintf('%0.55f',0.35)
When MATLAB stores the number 0.35 as a double, it actually stores a 52 binary bit approximation to 0.35. In terms of a decimal number, that value is seen above.
NEVER trust the least significant bits of a floating point number. At least not until you truly understand floating point arithmetic, and you then undertand why and when you can trust a number. Learn to use tolerances if you don't know the value.
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!