I've got an error in my Matlab looks like a bug
4 views (last 30 days)
Show older comments
Hi everybody I made a code like this :
m=(0:0.1:1.8);
m==0.6
and it returns ans =
1×19 logical array
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
but m(7) returns ans =
0.6000
I've tried this with 'find' function and I've got the same, by the way my friend also checked if they are doubles or not but they both are ...it looks like to be a Matlab's bug can you check this in your own ? ...any help will be appreciated.... thank you
0 Comments
Accepted Answer
OCDER
on 23 Jul 2018
https://www.mathworks.com/help/matlab/matlab_prog/floating-point-numbers.html Look at "Avoiding Common Problems with Floating-Point Arithmetic"
It's caused by a rounding error. Not a matlab bug, but an issue with any computer floating point math.
m=(0:0.1:1.8);
m==0.6
format longe
m(7)
ans =
6.000000000000001e-01 %that "1" at the way end is causing the m(7) == 0.6 to fail.
You need to use some sort of tolerance check
ismembertol(m, 0.6, eps*3)
ans =
1×19 logical array
0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0
0 Comments
More Answers (1)
Guillaume
on 23 Jul 2018
It's not a matlab bug. It is expected behaviour of floating point numbers that computers use and you need to learn the pitfall associated with these.
The solution, as explained in the FAQ is never to compare floating point numbers with == but compare their absolute difference against an arbitrary small value.
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!