Rem*_*i.b 3 random r distribution
目标
我正在尝试构建一个从"不完全均匀分布"中抽取特定数量的随机数的函数.
我称之为不完整的均匀分布?
我将不完整的均匀分布称为概率分布,其中X一系列边界内的每个值具有相同的拾取概率.换句话说,它是具有孔的均匀分布(其中概率为零),如下所示
x = list(12:25, 34:54, 67:90, 93:115)
y = 1/sum(25-12, 54-34, 90-67, 115-93)
plot(y=rep(y, length(unlist(x))), x=unlist(x), type="n", ylab="Probability", xlab="X")
for (xi in x)
{
points(xi,rep(y, length(xi)), type="l", lwd=4)
}
Run Code Online (Sandbox Code Playgroud)
难看的解决方案
这是一个缓慢而丑陋的解决方案
IncompleteUnif = function(n,b)
{
#################
# "n" is the desired number of random numbers
# "b" is a list describing the boundaries within which a random number can possibly be drawn.
#################
r = c() # Series of random numbers to return
for (ni in n)
{
while (length(r) < n) # loop will continue until we have the "n" random numbers we need
{
ub = unlist(b)
x = runif(1,min(ub), max(ub)) # one random number taken over the whole range
for (bi in b) # The following loop test if the random number is withinn the ranges specified by "b"
{
if (min(bi) < x & max(bi) > x) # if found in one range then just add "x" to "r" and break
{
r = append(r,x)
break
}
}
}
}
return (r)
}
b = list(c(5,94),c(100,198),c(220,292), c(300,350))
set.seed(12)
IncompleteUnif(10,b)
[1] 28.929516 287.132444 330.204498 63.425103 16.693990 66.680826 226.374551 12.892821 7.872065 140.480533
Run Code Online (Sandbox Code Playgroud)
您的不完全均匀分布可以表示为四个普通均匀分布的混合,每个分段的混合权重与其长度成比例(即,使得分段越长,其具有越多的重量).
要从这样的分布中进行采样,首先选择一个分段(考虑权重).然后从选定的段中选择一个元素.