Search code examples
c++prng

Would randomising the seed create a more random number?


I have three questions about RNG.

The first is what data is available to use as a seed. I have always used the time but there must be other easily available seeds.

What easily available seeds are there in c++?

If I reseeded the RNG at random intervals based on the next value to come out of the RNG and chose the seed at random from the answers to question 1 would this create a pseudo random chain that was harder to predict and therefore more random ?

Lastly what is the best way in c++ to get a random number within a range ? I have been using the modulus operator but I want something that will be evenly spread among the range and not favour high or low as it is fro the AI decisions.


Solution

    1. It depends on what you need rand for. For a lot of uses, time is perfectly adequate. For others less so. I'll usually read four bytes from /dev/random on a Unix machine, reverting to time if /dev/random isn't available. A more effective solution would be to use a higher resolution timer, and to hash in things like the process or the machine id.

    2. Reseeding probably won't change things much unless you're using something like /dev/random to do it. Most of the other available values are pretty predictable.

    3. If RAND_MAX is a multiple of the range, modulo works fine. If it isn't, the only solution is to throw away values: you have a total of RAND_MAX + 1 values, and you need n. And there is no possible mapping that will map all of the RAND_MAX + 1 values to n and have the same number of inputs for each n. The usual solution is something like:

        int limit = (RAND_MAX + 1) - (RAND_MAX + 1) % n;
        int result = rand();
        while ( result >= limit )
            result = rand();
        return result % n;
    

    (I'm supposing here that you're looking for a result in the range [0...n). And that RAND_MAX + 1 won't overflow.)

    Finally, if you're worried about the quality of the random values, be aware that many implementations of rand() aren't particularly good. You might want to switch to one of the boost random generators.