wierd behavior by find function

wierd behavior by find function

Post by Nikolaj An » Fri, 16 Mar 2007 19:13:28


I have a vector of unique numbers and want to find the index for a
certain number. Tried to use the find function, but it seems very
unstable. The problem is best described by an example:

Say I create the following vector: [0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8
0.9 1]. Then find(x==0.1) returns 2 and find(x==0.2) returns 3, but
find(x==0.3) returns en empty matrix!

Am I doing something wrong here, or have the find function just lost
its mind?
 
 
 

wierd behavior by find function

Post by Je » Fri, 16 Mar 2007 19:21:51

Hi,

read this:

http://www.yqcomputer.com/ @XXXXX.COM @

Je

 
 
 

wierd behavior by find function

Post by Je » Fri, 16 Mar 2007 19:23:07

and try this :

sprintf('%.20f\n',.1:.1:1)

Je
 
 
 

wierd behavior by find function

Post by Jos » Fri, 16 Mar 2007 19:53:39


as Jerome pointed out already, this is a common issue in floating
point arithmetic.

it also depends on how you created the vector:

x1 = [0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1]
x2 = 0:0.1:1

almost the same but see ...

x1==x2

Lesson: don't compare floating points using "==", but use a
tolerance:

abs(x1-x2)<eps

hth
Jos