2

I ran the following code in R version 3.1.2:

> 7 - (.05+.1)/.05
[1] 4
> rep(NA, 4)
[1] NA NA NA NA
> rep(NA, 7 - (.05+.1)/.05)
[1] NA NA NA   

Note that the last rep call returned 3 NAs instead of 4 even though 7 - (.05+.1)/.05 = 4. Can others replicate this same error? Is there a simple explanation for it?

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418

1 Answers1

2

7.31 Why doesn’t R think these numbers are equal?

The only numbers that can be represented exactly in R’s numeric type are integers and fractions whose denominator is a power of 2. Other numbers have to be rounded to (typically) 53 binary digits accuracy. As a result, two floating point numbers will not reliably be equal unless they have been computed by the same algorithm, and not always even then. For example

R> a <- sqrt(2)
R> a * a == 2
[1] FALSE
R> a * a - 2
[1] 4.440892e-16

The function all.equal() compares two objects using a numeric tolerance of .Machine$double.eps ^ 0.5. If you want much greater accuracy than this you will need to consider error propagation carefully.

If you're expecting a result to be an integer, you could force it to be a perfect one by using the round function:

7L - (.05+.1)/.05 == 4
[1] FALSE

round(7L - (.05+.1)/.05) == 4
[1] TRUE
codingEnthusiast
  • 3,800
  • 2
  • 25
  • 37