Biased Random Number Generator

前端 未结 10 457
春和景丽
春和景丽 2020-12-09 12:41

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 t

相关标签:
10条回答
  • 2020-12-09 13:41

    The Boost random number library provides the ability to specify different shaped distributions for your generator. It's a great library - see http://www.boost.org/doc/libs/1_42_0/libs/random/index.html.

    0 讨论(0)
  • 2020-12-09 13:44

    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  ...
    }
    
    0 讨论(0)
  • 2020-12-09 13:46
    #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:

    0 讨论(0)
  • 2020-12-09 13:47

    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.

    0 讨论(0)
提交回复
热议问题