Matlab: Double precision problem

In matlab, Sometimes when you try to compare two numbers, they don't usually gives you the answer you excepted. When you compare two integers,

a=1;
b=1;
a==b

will gives you 1.

but when you compare double, sometimes it doesn't work. Simple cases that if you do

a=0.001;
b=0.001;
a==b

will give you 1 still. But if you save a into a file, and use textread(filename) to get the value, the value may still look like 0.001, but if you do

a==0.001

It might give you 0 because the a was read from a file and it was in some weird format. This might be a bug. Some people fix it by doing

abs(a-0.001)<0.000001

it basically means if a and 0.001 is very close, then they are equal.

I personally have a quicker fix.

a+1==0.001+1.

For some reason, after any operation on the variable, the value no long have anything weird going on inside.

Loading Facebook Comments ...

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>