Biased Random Number Generator

2019-01-23 08:44发布

I am looking for a random number generator that can be biased. For instance, say I want a random number between 1-5, with the probability being:

1: Comes up 20% of the time
2: Comes up 10% of the time
3: Comes up 40% of the time
4: Comes up 25% of the time
5: Comes up 5% of the time

Is there anything in the standard library, or other libraries out there that would do this? Alternatively, is there an efficient way to do this myself?

标签: c++ random
10条回答
再贱就再见
2楼-- · 2019-01-23 09:15
#include <boost/random/discrete_distribution.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/variate_generator.hpp>

#include <iostream>

int main()
{

  unsigned int seed = 42;
  boost::mt19937 generator(seed);

  // return 0 with probability 10%
  //        1                  40%
  //        2                  50%
  boost::random::discrete_distribution<int> custom_dist{1,4,5};

  boost::variate_generator<boost::mt19937&,
  boost::random::discrete_distribution<int> > rndn(generator, custom_dist);

  for (unsigned int i = 0; i<10000; i++) {
    std::cout << rndn() << std::endl;
  }

  return 0;

}

And here is a plot of the result:

Output

查看更多
放荡不羁爱自由
3楼-- · 2019-01-23 09:16

Throw a random real number x in [0,1], if 0< x<0.2 return 1, if 0.2<x <0.3 return 2, etc.

See here for the general problem.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-23 09:18

Why don't you just use a regular random number generator that return number between 0.0 and 1.0, and wrap it with another function that returns a number according to your requirements?

like

double biased (double seed) {
if (seed >= 0.0 && seed <0.2) return 1;
else if  ...
}
查看更多
贪生不怕死
5楼-- · 2019-01-23 09:24

I am doing to do the same thing and I found this: http://eli.thegreenplace.net/2010/01/22/weighted-random-generation-in-python/

Seems good enough for the purpose you stated.

查看更多
登录 后发表回答