带有偏差的随机数

时间:2014-01-30 09:08:13

标签: c++ random numbers

所以我有一张地图< int,float>包含数字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。我猜猜字符串流与此有关。但我不知道如何知道随机数的限制,而不是通过将float转换为字符串然后获取具有最多字符的值。请帮忙。

1 个答案:

答案 0 :(得分:0)

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

E.g。偏差[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.