如何从R中的双变量已知PDF生成随机变量? [英] How to generate random variables from a bivariate known PDF in R?
问题描述
我在DX x DY矩形区域中具有此二元概率密度函数:
I have this bivariate probability density function in a DX x DY rectangular region:
我正在使用R.如何按照该pdf分布在矩形内生成随机(x,y)点?
I am using R. How can I generate random (x,y) points within the rectangle following this pdf distribution?
我已经阅读了许多有关逆变换采样"的答案,但是我没有单变量pdf.我已经见过此方法,但是看起来很乏味并且很难实现.
I have read many answers regarding "inverse transform sampling", but I don't have a univariate pdf. I have seen this method, but looks tedious and extremely difficult to implement.
提前谢谢!
推荐答案
这似乎更多是统计信息,而不是编程问题.无论如何,拒收抽样应适合您的情况.您可以在维基百科中阅读详细信息.以下函数执行拒绝采样(n ...个样本数; pdf ...概率密度函数; maxval ... pdf可产生的最大值(或更大); xlim,ylim ...边界框,其中密度函数产生值大于零):
This seems to be more of a statistical than a programming question. Anyway, rejection sampling should work in your case. You can read up the details at wikipedia. The following function performs rejection sampling (n...number of samples; pdf...probability density function; maxval...maximum (or bigger) value your pdf can yield; xlim, ylim... boundary box wherein density function yields values greater zero):
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)
}
例如,它可以用于二维正态分布
For instance, it can be used for the 2d normal distribution
mydens <- function(x,y)
{
dnorm(x)*dnorm(y)
}
以这种方式(此处定义的2d正态分布的最大值为x = 0,y = 0且小于0.16):
in that way (the maximum value of the here defined 2d normal distribution is at x=0,y=0 and a bit smaller than 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值.对于此x值,请使用条件概率分布(给定获得的x,y的概率),然后再次对i值使用逆变换采样.
p.s. You can also use inverse transform sampling. Calculate the marginal distribution along i.e. the x-axis. Use this distribution for inverse transform sampling to get an x-value. For this x-value use the conditional probability distribution (probability for y given the obtained x) and use inverse transform sampling again, now for the y-value.
这篇关于如何从R中的双变量已知PDF生成随机变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!