1

I'm getting strange behavior where matrix dimensions are not working as expected here is a toy example

n <- 10     
delt <- 0.00001
s <- n/delt + 1
print(s)

s = 1000001

x <- matrix(0, nrow = s, ncol = 2)
dim(x)

1000000 2

However, if I type

x <- matrix(0, nrow = 1000001, ncol = 2)
dim(x)

I get what I expect 1000001 2

WetlabStudent
  • 2,556
  • 3
  • 25
  • 39

1 Answers1

2

This is why:

print(s,digits=20L); ## s is slightly under 1000001 after all
## [1] 1000000.9999999998836
as.integer(s); ## truncates to 1000000
## [1] 1000000

The documentation on matrix() doesn't explicitly say it, but the nrow and ncol arguments are internally coerced to integer.

Also see Why are these numbers not equal?.

Community
  • 1
  • 1
bgoldst
  • 34,190
  • 6
  • 38
  • 64
  • 1
    I see, the coercion truncates instead of rounds so have to watch out for numerical error (especially when dividing by such a small number). – WetlabStudent May 26 '16 at 04:36