7

Possible Duplicate:
Numeric comparison difficulty in R

Hello All,

According to "R Inferno" paper. I'm right now in the first circle of R hell. This is where pagans expect 0.1 == 0.3/3. Paper recommends using all.equal function for such cases, however I need to check ">=" or "<=" conditions. With current example on of them fail:

> .1 >= .3/3
[1] TRUE
> .1 <= .3/3
[1] FALSE

Is there a similar function to all.equal that checks inequalities?

Thank you,

Ilya

Community
  • 1
  • 1
ilya
  • 3,124
  • 2
  • 26
  • 26
  • 4
    That's not an R specific error, but a common error that is caused by the binary representation of floating point numbers. See http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems for example. – schnaader Nov 02 '10 at 15:17
  • 1
    I know why error occurs. I would like to know if there is a R function that can check inequalities or I need to write one with floating points in mind. – ilya Nov 02 '10 at 15:22
  • 1
    yes, I need to do better searches – ilya Nov 02 '10 at 15:35
  • 2
    High popularity like for exact duplicate. Catchy title? – Marek Nov 02 '10 at 15:57

4 Answers4

10

The main test of all.equal is whether abs(x-y) < tolerance for some values x and y and some small tolerance. Equivalent inequality tests would check:

x <= y:         x-y < tolerance
x < y:          x-y < -tolerance
x >= y:         x-y > -tolerance
x > y:          x-y > tolerance
mob
  • 117,087
  • 18
  • 149
  • 283
9

See these questions:

Generally speaking, you can deal with this by including a tolerance level as per the second link above.

Community
  • 1
  • 1
Shane
  • 98,550
  • 35
  • 224
  • 217
6

Please see the R FAQ entry Why doesn't R think these numbers are equal and the references therein.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • 2
    This is fascinating, but not an answer to the OP. – mob Nov 02 '10 at 15:24
  • 4
    Sure is, or you read another entry 7.31. The example there is `sqrt(2)*sqrt(2) == 2` comes out as FALSE and is the same issue here: representation of floating point numbers. – Dirk Eddelbuettel Nov 02 '10 at 15:28
4

You could try judicious use of zapsmall() which seems to give the behavior you are looking for. I don't know if this works in all situations. e.g.,

.1 >= zapsmall(.3/3)
[1] TRUE
> .1 <= zapsmall(.3/3)
[1] TRUE
kmm
  • 6,045
  • 7
  • 43
  • 53