1
minls<- -5.74
maxls<- 1.97
sseq<-seq(minls,maxls,0.5)
which(sseq==-0.24)

which(sseq==-0.24) gives output numeric(0)

To test sseq

 [1] -5.74 -5.24 -4.74 -4.24 -3.74 -3.24 -2.74 -2.24 -1.74 -1.24 -0.74 -0.24  0.26  0.76  1.26  1.76

As you can see the 12th element is -0.24

Simply creating an array by c(...) does not give this error

Is there something incorrect I am doing or is this a problem with the which() function, is there any alternative to which()

skr
  • 452
  • 6
  • 21

3 Answers3

4

You are facing numerical approximation issues.

try sseq == -0.24 or sseq+0.24.

There you will notice that none of the values in sseq is exactly -0.24. So the problem has nothing to do with which, only with the fact that computers cannot represent all numbers exactly.

Arun
  • 116,683
  • 26
  • 284
  • 387
Nick Sabbe
  • 11,684
  • 1
  • 43
  • 57
3

It is probably due to floating point issue. You could use all.equal to check with a threshold (tolerance parameter of this function).

# tolerance is default - .Machine$double.eps ^ 0.5
chk <- apply(as.matrix(sseq), 1, function(x) {
    ifelse(all.equal(x, -0.24) == "TRUE", TRUE, FALSE)
})
which(chk)
# [1] 12
Arun
  • 116,683
  • 26
  • 284
  • 387
2

Similarly to @Arun answer, you can also do

# Change 1e-9 to whatever tolerance suits you best
which(abs(sseq-(-0.24)) < 1e-9)
nico
  • 50,859
  • 17
  • 87
  • 112
  • aha.. clever.. I did `abs(seq)+0.24` and realised soon that it'll also give out positive values closer to 0.24. I had to change to `all.equal`. (+1). – Arun Mar 19 '13 at 09:12