r - 从均匀分布的混合中抽取随机数

标签 r random 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)
}

enter image description here

丑陋的解决方案

这是一个缓慢而丑陋的解决方案
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

最佳答案

您的不完全均匀分布可以表示为四种普通均匀分布的混合,每个段的混合权重与其长度成正比(即,段越长,权重越大)。

要从这样的分布中取样,首先选择一个段(考虑权重)。然后从所选段中选择一个元素。

关于r - 从均匀分布的混合中抽取随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34443195/

相关文章:

regex - 如何在 R 中 gsub ('%' 、 '\%' 、...?

python - 如何加速 Poisson pmf 函数?

ios - inHouse 和 appStore 分发配置文件之间的冲突

java - 如何在java中随机绘制的图像上添加mouselistener?

c# - 如何获得随机 A-Z 字母数组?

python - 如何在 Python 中创建 logit 正态分布?

r - 将图像和数据从 R 导出到 Excel 电子表格

r - 我在哪里可以找到 R 中 Kolmogorov-Smirnov 距离的极限分布?

r - 计算直方图或密度函数中的峰

r - 如何最好地使用其概率函数模拟任意单变量随机变量?