【问题标题】:Random Sampling with Distance Condition具有距离条件的随机抽样
【发布时间】:2017-01-24 23:22:53
【问题描述】:

我想从区间 [1,N] 中随机抽取两个整数 x 和 y,使得 |x-y| >= D,对于某些 D

N <- 100; D <- 10;

i <- sample(1:N, 2)

while ( abs( i[1] - i[2] ) < D ){
   i <- sort(sample(1:N, 2))
}

【问题讨论】:

  • 似乎一点也不低效——你为什么这么说?对于 10 的距离和 1 到 100 的值,大多数时候您只需调用一次 sample
  • 我猜(in)效率取决于具体的用例,但最重要的是这个算法不是恒定时间,因为P(|x-y| &gt;= D) 对 sample(1:N, 2) 的任何调用都是沿着1 - [(N-x)/N + (x-0)/N + 2D/N] 的行,其中 P(x) = 1/N,对于 [1:N] 中的任何 x,y 且 D

标签: r random


【解决方案1】:

我想关键是要意识到 y 依赖于 x(或相反)。以下是最多三个步骤的算法:

1. sample x from [1:N]
2. sample y from [1:(x-D)] if (x-D) >= 1
   sample y from [x + D:N] if (x+D) <= N
3. If both conditions for y are met, choose one of the generated y  uniform at random

这个想法是,一旦 x 被采样,y 需要在 [1:(x-D)] 或 [x+D:N] 范围内以满足 |x-y| >= D。

例子:

N=100; D=10

a) x is close to N

1. x is sampled from 1:N as 95
2. to satisfy |x-y| >= D, y can be at most 85, so the range to sample y is [1:85]

b) x is close to 1

1. x is sampled from 1:N as 9
2. y must be at least 19, so the range to sample y is [19:N]

c) x is close to 50

1. x is sampled from 1:N as 45
2. y must be either at most 35, or at least 55, so the ranges to sample from are [1:35] and [55:N]

【讨论】:

    【解决方案2】:

    我将通过首先随机抽样大于或等于D 的数字之间的差异来解决此问题。换句话说,我们希望对DN-1 之间的数字进行替换。

    difference <- sample(D:(N-1), 20, replace = TRUE)
    

    现在我们需要做的就是通过在1N - difference 之间选择一个数字来选择我们的较小数字。我们可以使用vapply 来做到这一点。

    lowerval <- vapply(N - difference, sample, numeric(1), 1)
    

    最后我们通过将差值与下限值相加得到上限值。

    upperval <- lowerval + difference
    

    【讨论】:

    • 需要注意的一点是,使用此算法的分布与使用 OP 算法的分布不同。因此,根据随机抽样所需的任何其他要求,这可能是也可能不是他们想要的。
    猜你喜欢
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-14
    • 2016-09-06
    相关资源
    最近更新 更多