Matching quantitive values

3) Some of you have emailed me regarding matching on numeric values. In general, it is not a good idea to try to use == on quantitative numeric (non-integer) values.

This is because numeric values are stored as double precision. Although it looks like 5.1, it may actually be 5.1000001 which will cause no match when you compare it to 5.1. It is actually stored to eight decimal places (+/- 10^-8). Itʻs perfectly fine to use == for discrete values (like index numbers which are integers, or factors or characters), but do not use them for quantitive values or you may be surprised.

Here is an example of where this might come up.

x <- seq( from=0, to=50, by=0.1)
which(x==5.5) # works
which(x==5.1) # doesnʻt work
which(x==5.3) # doesnʻt work

Instead, use:

which(x>5.0 & x<5.2 ) # Better way

Of course it may return more than one index. You can just take the mean index:
which( x>4.9 & x<5.3 )
[1] 51 52 53

ii <- which( x>4.9 & x<5.3 )
mean(ii)
[1] 52

Of course rather than using actual fixed numbers, you may want to have a guess for x called P_x and test in a small neighborhood around that point. So if your delta is .1, you could code it as:

> ii <- which((x>P_x-delta) & (x<P_x+delta))

mean(ii)

If you are concerned about getting an even number (and resulting in a mean with a .5 ending, just round down:

> ii <- floor(mean(ii))

Then the coordinates of for example your guess would be:

> P_x <- x[ii]

P_fx <- fx[ii]

If you create a vector of derivatives, you can also use ii to index that as well:

> dx <- derivative[ii] # if you store your vector of derivatives in “derivative”

Marguerite