使用随机数生成器生成具有给定期望值的数字 [英] Using random number generator to generate a number with a given expected value

查看:102
本文介绍了使用随机数生成器生成具有给定期望值的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下问题:

使用 rand() 函数,生成一个期望值为 k 的数字.选项是:

Using rand() function, generate a number with expected value k. Options are:

1)

   int GetRandom(int k)
   {
       v=0;
       while(rand()<1.0f/(float)k)
           v++; 
       return v;
    }

2)

   int GetRandom(int k)
   {
       v=0;
       while(rand()<(1-1.0f/(float)k))
           v++; 
       return v;
    }

3)

   int GetRandom(int k)
   {
       v=0;
       while(rand() > (1-1.0f/(float)(k+1)))
           v++; 
       return v;
    }

1) 似乎是正确的答案.检查 k 的特定值的结果似乎表明情况并非如此.(我设置了 k=3.100000 次试验值的频率分布可以在下图中看到 )

1) seemed like the correct answer. Examining the outcome for specific values of k seems to indicate this is the not the case. (I set k=3. The frequency distribution of values for 100000 trials can be seen in the image below )

如何做到这一点?

这个问题有点类似于这个.

推荐答案

你想要 (2).这对 Geometric Distribution (link) 进行采样,均值为 k.

You want (2). This samples a Geometric Distribution (link) with mean k.

几何分布代表此类实验:

A geometric distribution represents an experiment of this kind:

  • 某个事件重复发生,结果为 0 或 1
  • 事件的结果是 1 的概率 p 和 0 的概率 1-p
  • 第一个结果为 1 的事件的索引是多少?

所以如果X ~ G(p),其中X是一个随机变量,p是上面的概率,那么X 表示第一个结果为 1 的事件的索引是多少?"期望是E[X] = 1/p.

So if X ~ G(p), where X is a random variable and p is the probability above, then X represents "What is the index of the first event with an outcome of 1?" The expectation is E[X] = 1/p.

鉴于此信息,现在应该清楚以下表示随机变量 X 的抽样,其中 p = 1/k(等价于 (2)).

Given this information it should now be clear that the following represents a sampling of the random variable X with p = 1/k (and is equivalent to (2)).

int Sample(int k)
{
    int v = 1;
    while (true)
    {
        //outcome is true with probability p = 1/k
        bool outcome = rand() < 1 / (double)k;
        if (outcome)
            return v;
        else
            v++;
    }
}

请注意,查看分布的峰值(众数)和期望值不是一回事.几何分布的峰值总是在 1!

Be aware that looking at the peak (mode) and expectation of the distribution are not the same thing. The peak of the geometric distribution is always going to be at 1!

这篇关于使用随机数生成器生成具有给定期望值的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆