2014-01-30 44 views
0

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

+1

C++有一个更好的随机库'',它明确支持非均匀分布。现在你需要编写你自己的发行版,因为它对你的情况很特殊,但只需要覆盖发行版的一部分 - 而不是随机数生成部分。 – MSalters

+1

在生成每个数字之前调用'srand'并没有帮助。如果你坚持'rand',那么在程序开始时调用'srand'一次。 –

回答

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.