-1

I want to check if a series of numbers multiplying a number n are integers. However, when I use the seq function to develop this series and multiply n, then checking if it is a integer sequence, I will find something wrong, such as the following example. Please help me to figure out this question!

x <- seq(from=0.001, to=0.015, by=0.001)
x
[1] 0.001 0.002 0.003 0.004 0.005 0.006 0.007 0.008 0.009 0.010 0.011 0.012 0.013 0.014 0.015
n <- 1000
a = x[9]*n
a
[1] 9
a == 9
[1] FALSE

1 Answers1

1

Floating math operations in R may give surprising results in R, as in your example.

Using your code, you will see that there is a very small difference between the the variable a and 9 (note that the exact value you see may vary):

a-9   # yields 1.776357e-15

You can deal with this by comparing the difference to a very small value:

abs(a-9) < 1e-10  # yields TRUE

You will find the compare library useful

library(compare)
compare(a,9)      # yields TRUE
jafelds
  • 894
  • 8
  • 12
  • 1
    just to point out that floating point comparisons in *any* computer language may be similarly surprising. `all.equal()` may be useful too. – Ben Bolker Dec 10 '14 at 15:34