Why I obtain wrong answer when using “==”<>
This question already has an answer here:
- Why are these numbers not equal? 3 answers
Try this to first see what's going on:
x <- seq(0, 20, 0.5) sprintf("%.20f", x) # convert value to string with 20 decimal places #  "14.50000000000000000000" x == 14.5 #  TRUE
All is well so far. Now, try this:
x <- seq(0, 20, 0.05) sprintf("%.20f", x) # convert value to string with 20 decimal places #  "1.45000000000000017764" x == 1.45 #  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 and 1.45... is < this threshold, then all.equal evaluates this to TRUE.
all.equal(x, 1.45)  TRUE
Another way of doing this is to explicitly check with a specific threshold (as @eddi's answer shows it). Hope this helps.