Sop*_*lan 7 simulation r probability sampling
我想申请的甩采样方法来模拟随机矢量Y=(Y_1, Y_2)从一个单元盘状的均匀分布的D = { (X_1 , X_2) \in R^2: \sqrt{x^2_1 + x^2_2} ? 1},使得X = (X_1 , X_ 2)处于正方形的均匀分布的随机矢量S = [?1, 1]^2和接头密度f(y_1,y_2) = \frac{1}{\pi} 1_{D(y_1,y_2)}.
在拒绝方法中,我们一般接受一个样本如果f(x) \leq C * g(x)。我正在使用以下代码:
x=runif(100,-1,1)
y=runif(100,-1,1)
d=data.frame(x=x,y=y)
disc_sample=d[(d$x^2+d$y^2)<1,]
plot(disc_sample)
Run Code Online (Sandbox Code Playgroud)
我有两个问题:
{使用上面的代码,从逻辑上讲,的大小d应该大于的大小,disc_sample但是当我调用它们时,我看到它们中的每一个都有 100 个元素。这怎么可能。为什么尺寸相同。}这部分已解决,感谢下面的评论。
现在的问题
另外,我怎样才能重新编写我的代码,以便为我提供按照条件获取 100 个样本所需的样本总数。即给我拒绝的样品数量,直到我得到 100 个所需的样品?
感谢r2evans的回答,但我希望写一些更简单的东西,一个 while 循环将所有可能的样本存储在矩阵或数据帧而不是列表中,然后从该数据帧调用,只是样本遵循条件。我在没有使用列表和 sapply 函数的情况下修改了答案中的代码,但它没有给出所需的结果,它只产生一行。
i=0
samps <- data.frame()
goods <- data.frame()
nr <- 0L
sampsize <- 100L
needs <- 100L
while (i < needs) {
samps <- data.frame(x = runif(1, -1, 1), y = runif(1, -1, 1))
goods <- samps[(samps$x^2+samps$y^2)<1, ]
i = i+1
}
Run Code Online (Sandbox Code Playgroud)
我也想过这个:
i=0
j=0
samps <- matrix()
goods <- matrix()
needs <- 100
while (j < needs) {
samps[i,1] <- runif(1, -1, 1)
samps[i,2] <- runif(1, -1, 1)
if (( (samps[i,1])**2+(samps[i,2])**2)<1){
goods[j,1] <- samps[i,1]
goods[j,2] <- samps[i,2]
}
else{
i = i+1
}
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用。
对于修改代码的任何帮助,我将不胜感激。
至于你的第二个问题......你无法重新编写你的代码来准确地知道需要多少个组合才能获得(至少)100 个结果组合。您可以使用while循环并连接结果,直到至少有 100 个这样的行,然后截断超过 100 行。因为分段使用熵(大规模)是“昂贵的”,所以您可能更愿意始终高估所需的行,并且一次性全部抓住。
(根据作业限制进行编辑以减少“复杂性”。)
set.seed(42)
samps <- vector(mode = "list")
goods <- vector(mode = "list")
nr <- 0L
iter <- 0L
sampsize <- 100L
needs <- 100L
while (nr < needs && iter < 50) {
iter <- iter + 1L
samps[[iter]] <- data.frame(x = runif(sampsize, -1, 1), y = runif(sampsize, -1, 1))
rows <- (samps[[iter]]$x^2 + samps[[iter]]$y^2) < 1
goods[[iter]] <- samps[[iter]][rows, ]
nr <- nr + sum(rows)
}
iter # number of times we looped
# [1] 2
out <- head(do.call(rbind, goods), n = 100)
NROW(out)
# [1] 100
head(out) ; tail(out)
# x y
# 1 0.8296121 0.2524907
# 3 -0.4277209 -0.5668654
# 4 0.6608953 -0.2221099
# 5 0.2834910 0.8849114
# 6 0.0381919 0.9252160
# 7 0.4731766 0.4797106
# x y
# 221 -0.65673577 -0.2124462
# 231 0.08606199 -0.7161822
# 251 -0.37263236 0.1296444
# 271 -0.38589120 -0.2831997
# 28 -0.62909284 0.6840144
# 301 -0.50865171 0.5014720
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
93 次 |
| 最近记录: |