Generating random integer from a range

前端 未结 13 1524
失恋的感觉
失恋的感觉 2020-11-22 03:12

I need a function which would generate a random integer in given range (including border values). I don\'t unreasonable quality/randomness requirements, I have four requirem

13条回答
  •  青春惊慌失措
    2020-11-22 04:01

    How about the Mersenne Twister? The boost implementation is rather easy to use and is well tested in many real-world applications. I've used it myself in several academic projects such as artificial intelligence and evolutionary algorithms.

    Here's their example where they make a simple function to roll a six-sided die:

    #include 
    #include 
    #include 
    
    boost::mt19937 gen;
    
    int roll_die() {
        boost::uniform_int<> dist(1, 6);
        boost::variate_generator > die(gen, dist);
        return die();
    }
    

    Oh, and here's some more pimping of this generator just in case you aren't convinced you should use it over the vastly inferior rand():

    The Mersenne Twister is a "random number" generator invented by Makoto Matsumoto and Takuji Nishimura; their website includes numerous implementations of the algorithm.

    Essentially, the Mersenne Twister is a very large linear-feedback shift register. The algorithm operates on a 19,937 bit seed, stored in an 624-element array of 32-bit unsigned integers. The value 2^19937-1 is a Mersenne prime; the technique for manipulating the seed is based on an older "twisting" algorithm -- hence the name "Mersenne Twister".

    An appealing aspect of the Mersenne Twister is its use of binary operations -- as opposed to time-consuming multiplication -- for generating numbers. The algorithm also has a very long period, and good granularity. It is both fast and effective for non-cryptographic applications.

提交回复
热议问题