If I type:
x<-seq(0,20,.05)
x[30]
x[30]==1.45
Why do I obtain a False
from the last line of code? What did I do wrong here?
If I type:
x<-seq(0,20,.05)
x[30]
x[30]==1.45
Why do I obtain a False
from the last line of code? What did I do wrong here?
This question has been asked a million times, albeit in different forms. This is due to floating point inaccuracy. Also here's another link on floating point errors you may want to catch up on!
Try this to first see what's going on:
x <- seq(0, 20, 0.5)
sprintf("%.20f", x[30]) # convert value to string with 20 decimal places
# [1] "14.50000000000000000000"
x[30] == 14.5
# [1] TRUE
All is well so far. Now, try this:
x <- seq(0, 20, 0.05)
sprintf("%.20f", x[30]) # convert value to string with 20 decimal places
# [1] "1.45000000000000017764"
x[30] == 1.45
# [1] FALSE
You can see that the machine is able to accurately represent this number only up to certain digits. Here, up to 15 digits or so. So, by directly comparing the results, you get of course a FALSE. Instead what you could do is to use all.equal
which has a parameter for tolerance which equals .Machine$double.eps ^ 0.5
. On my machine this evaluates to 1.490116e-08
. This means if the absolute difference between the numbers x[30]
and 1.45...
is < this threshold, then all.equal
evaluates this to TRUE.
all.equal(x[30], 1.45)
[1] TRUE
Another way of doing this is to explicitly check with a specific threshold (as @eddi's answer shows it).