1

Can anyone explain the following:

> any(seq(from=-10.1,to=10.1,by=0.1)==0)
[1] FALSE

> any(seq(from=-1.1,to=1.1,by=0.1)==0)
[1] TRUE

This confuses me a lot. It has probably something to do with floating point precision in R, but I am not able to wrap my head around it.

If you print the sequences, in the first case 0 is represented as 0 and in the second it's 1.776357e-15. But why is the switch from 1.1 to 10.1 invoking this behaviour. Both numbers are float anyway. right?

maRtin
  • 6,336
  • 11
  • 43
  • 66
  • Most likely because the error due to the FP precision on each sum of the first case (i.e. `-10.1 + 0.1 + 0.1 ...`) cumulates differently than the second case, and in the second case luckily the sum leads to zero... – digEmAll May 26 '17 at 13:10
  • 1
    That's the reason why programmers keep saying that `FP_NUM1 == FP_NUM2` should be avoided. You should do `abs(FP_NUM1-FP_NUM2) < tinynum (e.g. 1e-13)` instead – digEmAll May 26 '17 at 13:12
  • @digEmAll thanks for the explanation – maRtin May 28 '17 at 10:44

0 Answers0