2

I was doing some simulations in R and I noticed I was missing exactly one simulation, after looking into my code I discovered this strange R behaviour:

N <- 10000
prop <- 0.9
M <- N * (1 - prop)
print(M)
[1] 1000
print(as.integer(M))
[1] 999
ArturoSaCo
  • 319
  • 1
  • 10

1 Answers1

4

The issue is that 0.9 cannot be represented exactly as a binary floating-point value:

> sprintf('%.20f', 0.9)
[1] "0.90000000000000002220"

All the calculations that follow give inexact results:

> sprintf('%.20f', 10000 * (1 - 0.9))
[1] "999.99999999999977262632"
NPE
  • 486,780
  • 108
  • 951
  • 1,012