【问题标题】:Random number with biases有偏差的随机数
【发布时间】:2014-01-30 09:08:12
【问题描述】:

所以我有一个包含数字 1 - 6 偏差的地图。我需要返回一个有偏差的值。请注意,偏差不是恒定的,因为它们是由用户输入的。它在一个类中,因此所有变量都已声明。

这就是我到目前为止所做的。

    int die:: randomNumber(map < int, float >  &biasPercent)
    {
       randomString[0] << biasPercent[0];
       randomArray[0] = randomString[0].str();
       maximum = randomArray[0].size();

       for(counter = 0; counter < 6; counter++)
       {
          randomString[counter] << biasPercent[counter];
          randomArray[counter] = randomString[counter].str();

          if(randomArray[counter].size() > maximum)
          {
             maximum = randomArray[counter].size();
          }
       }

       limit = 1;



       for(counter = 1; counter <= maximum - 2; counter++)
       {
           limit *= 10;
       } 

       srand(time(NULL));

       random1 = rand() % limit + 1;

       if(random1 <= biasPercent[0] * limit)
       {
           return 1;
       }

       else if(random1 > biasPercent[0] * limit && random1 <= (biasPercent[0] * limit) + (biasPercent[1] * limit))
       {
           return 2;
       }

       else if(random1 > ((biasPercent[0] * limit) + (biasPercent[1] * limit) * limit) && random1 <= (((biasPercent[0] * limit) + (biasPercent[1] * limit)) + (biasPercent[2] * limit)))
       {
           return 3;
       }

       else if(random1 > (((biasPercent[0] * limit) + (biasPercent[1] * limit)) + (biasPercent[2] * limit)) && random1 <= (((((biasPercent[0] * limit) + (biasPercent[1] * limit)) + (biasPercent[2] * limit))) + (biasPercent[3] * limit)))
       {
          return 4;
       }

       else if(random1 > (((((biasPercent[0] * limit) + (biasPercent[1] * limit)) + (biasPercent[2] * limit))) + (biasPercent[3] * limit)) && random1 <= ((((((biasPercent[0] * limit) + (biasPercent[1] * limit)) + (biasPercent[2] * limit))) + (biasPercent[3] * limit))) + ((biasPercent[4] * limit)))
       {
          return 5;
       }

       else
       {
          return 6;
       }
    } 

它似乎不起作用,因为它一直只返回 1。我猜 stringstream 与此有关。但是我不知道如何知道随机数的限制,而不是通过将浮点数转换为字符串然后获取具有最多字符的值。请帮忙。

【问题讨论】:

  • C++ 有一个更好的随机库&lt;random&gt; 明确支持非均匀分布。现在您需要编写自己的发行版,因为它特定于您的情况,但这只需要涵盖发行版部分 - 而不是随机数生成部分。
  • 在生成每个号码之前调用 srand 并没有帮助。如果您坚持使用rand,请在程序开始时调用一次srand

标签: c++ random numbers


【解决方案1】:

最简单的解决方案是计算所有偏差的partial_sum。最后一个元素是偏差的总和。现在生成一个值为 [0, sum] 的随机数(使用 uniform_real_distribution),并在您的 partial_sum 中找到 upper_bound 的索引。

例如偏差 [0.2, 0.5, 6, 2, 3, 0.1] 给出 partial_sum [0.2, 0.7, 6.7, 8.7, 11.7, 11.8] 所以生成一个介于 0 和 11.8 之间的数字。假设是 4.378,上限是 6.7(第三个元素),因此结果是 3。

【讨论】: