c++ - 生成随机分布的更有效方法?

标签 c++ math random

是否有更有效、可能更数学化且更少算法的方法来实现与此类似的随机数分布?

unsigned int weighted_random_UINT()
{
    float r2 = 1;
    while(rand() % 4 != 0) // 3/4 chance
    {
        r2 *= fmod(
            ((float)rand()/RAND_MAX)+1, // random float between 1 and 2
            (float)UINT_MAX
        );
    }
    return (unsigned int)r2 - 1;
}

下面是 while 内部的安全性较低但更易于阅读的版本。

r2 *= ((float)rand()/RAND_MAX)+1;


分布可视化: the distribution visualized
问题中更平滑的解决方案(第 1 张图)与最佳答案中更快的解决方案(第 2 张图)之间的比较: comparison http://with-logic.co.uk/a/graph.png

最佳答案

我认为你不必循环遍历它,但一次就足够了,如下所示:

unsigned int weighted_random_UINT()
{
    float r2 = ((float)rand()/RAND_MAX)+1; // random float between 1 and 2
    unsigned int k = 0;
    while(rand() % 4 != 0) // 3/4 chance
    {k = k < UINT_MAX ? k + 1: UINT_MAX;}
    return (unsigned int)fpow(r2,(float)k) - 1;
}

第一部分是几何分布,最后一部分是均匀分布。 你想要 (1+U(0,1))^G(3/4)

虽然应该可以找到一些更快的方法来找到 G(3/4)。

编辑: 我在维基百科上找到了它: http://en.wikipedia.org/wiki/Geometric_distribution#Related_distributions

G(p)=floor(ln(U)/ln(1-p))

因此你想要:

U^floor(ln(U)/ln(1-3/4))

这应该只是对 rand 的两次调用。

关于c++ - 生成随机分布的更有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7475415/

相关文章:

Perl 高尔夫 : Print the powers of a number

javascript - 生成 100 的随机倍数

java - JAVA数组内不重复的随机数

c++ - 可以将 &my_boost_array_variable[2] 传递给期望 void* 的 C 函数吗?

c++ - 当我们在两个结构上使用 = 运算符时,它会做什么?

c++ - 将 bool 标志更改为模板参数

c++ - 将 iPhone 游戏移植到 Android - 纹理和缓冲区

Java行星轨道模拟: centering planets

python - 计算包含范围内所有值的函数?

python - 我可以在生成随机值时指定一个 numpy dtype 吗?