Question

Using GLM 0.9.5.1 I'm generating random numbers at launch with glm::linearRand(-1.0f, 1.0f). It looks like everytime I restart the application the values are always the same. Maybe I'm missing a function in GLM to reseed the random number generator?

Have a look at this code:

std::cout << glm::linearRand(-1.0f, 1.0f) <<  std::endl;
std::cout << glm::linearRand(-1.0f, 1.0f) <<  std::endl;
std::cout << glm::linearRand(-1.0f, 1.0f) <<  std::endl;
std::cout << glm::linearRand(-1.0f, 1.0f) <<  std::endl;

0.188513
0.428694
0.372967
-0.419843

These values are always the same. How would I reseed?

Was it helpful?

Solution

According to this source here:

https://github.com/Groovounet/glm/blob/master/glm/gtc/random.inl#L32

the random number generator uses std::rand() - in other words the C runtime library's random number generator. How well that is implemented depends on the actual C runtime library you are using. But it's typically written for "speed" rather than "accuracy" (in other words, it's probably ok for simple games, but if you want something that holds up in a commercially sensitive environment [e.g. online poker where the player wins real money], you probably want to use something better).

However, the reason you get the same values each time you run your program is because the default behaviour of the C runtime library is to start with the same seed. This is good for testing purposes where you may want something to behave the same each time you run the code. Calling srand(time(0)); once at the start of your code will put a seed into the random number generator, based on the current time. It's not perfect, but over a few minutes it will change quite a bit and make for a reasonably good "new set of random numbers each time". If you want "more random seed", you could use other methods, such as writing the current time as a string and hashing it with md5, perhaps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top