0

A strange behavior of the mvrnorm() function occured to me as I tried to make some calculation in one of the arguments.

This does do the job:

mvrnorm(
  n=200,
  mu = c('x'=0,'y'=0), 
  Sigma = matrix(c(1,0.5,0.5,1),nrow = 2), 
  empirical = TRUE)

Yet, replacing n = 200 with n = (1-0.8)*1000, does NOT do the job:

mvrnorm(
  n=(1-0.8)*1000,
  mu = c('x'=0,'y'=0), 
  Sigma = matrix(c(1,0.5,0.5,1),nrow = 2), 
  empirical = TRUE)

Error in eS$vectors %*% diag(sqrt(pmax(ev, 0)), p) %*% t(X) : 
  non-conformable arguments
In addition: Warning message:
In matrix(rnorm(p * n), n) :
  data length [399] is not a sub-multiple or multiple of the number of rows [199]

Why is this hapening?

Rtist
  • 3,825
  • 2
  • 31
  • 40
  • 1
    It looks like a floating point problem. Try typing `floor((1-0.8)*1000)` into the console. It gives 199, not 200. – Allan Cameron Feb 15 '22 at 14:36
  • 3
    [This](https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal/9508558#9508558) might help illuminate the floating point problem. – DaveArmstrong Feb 15 '22 at 14:37
  • Thanks, uses as as.integer ideed worked. Can you add it as an answer and explain why is this happening? And why floor((1-0.8)*1000 ginves 199? – Rtist Feb 15 '22 at 14:39
  • The question and answers that @DaveArmstrong explain very well why this happens. The answer to 1000 * (1 - 0.8) is stored as a floating point number, not as an integer, so it's not exactly 200. In this case, it's a tiny fraction less than 200. Your code fails here because `mvrnorm` calls `matrix` with the value of `n` passed to the `nrow` argument. This has to be rounded (down) before being passed as an `int` to the internal C code. Essentially, this question is a duplicate, albeit a slightly obscured one, and I don't think it warrants a separate answer. – Allan Cameron Feb 15 '22 at 14:46

0 Answers0