How to create random variables from two-dimensional well-known PDF to R?

I have this two-dimensional probability density function in the rectangular domain DX x DY:

Link to my pdf

I am using R. How can I generate random (x, y) points inside a rectangle after this PDF distribution?

I read a lot of answers regarding the "inverse transform sample", but I don't have a one-dimensional pdf. I have seen this method , but it looks tiring and extremely difficult to implement.

Thank you in advance!

+2
source share
1 answer

, . , . wikipedia. (n... , PDF... ; maxval... ( ) , pdf, xlim, ylim... , ):

reject.sample.2d <- function(n,pdf,maxval,xlim,ylim)
{
  smpl <- data.frame(x=numeric(n),y=numeric(n))
  i <- 0
  while (i<n)
  {
    xval <- runif(1,xlim[1],xlim[2])
    yval <- runif(1,ylim[1],ylim[2])
    if (runif(1)<pdf(xval,yval)/maxval)
    {
      i <- i+1
      smpl[i,] <- c(xval,yval)
    }
  }
  return(smpl)
}

, 2d

mydens <- function(x,y)
{
  dnorm(x)*dnorm(y)
}

( 2d x = 0, y = 0 0,16):

res <- reject.sample.2d(5000,mydens,0.16,c(-5,5),c(-5,5))

:

> sd(res[["x"]])
[1] 1.015413
> sd(res[["y"]])
[1] 0.9981738

> shapiro.test(res[["x"]])

    Shapiro-Wilk normality test

data:  res[["x"]]
W = 0.9995, p-value = 0.1603

> shapiro.test(res[["y"]])

    Shapiro-Wilk normality test

data:  res[["y"]]
W = 0.9997, p-value = 0.8304

p.s. . . , x. x ( y x) , y-.

+5

Source: https://habr.com/ru/post/1627615/


All Articles