I am taking a course on programming, and we're using C++. We had an assignment where, at some point, we needed to code a function that would return a random number in an [upper, lower] interval. I used the following:
lower + (int) (upper * (rand() / (RAND_MAX + 1.0)));
I did not forget to change srand by using srand((unsigned int) time(0)).
However, I get the same value every time! I asked my professor for help and he, after some investigation, found out that the first number generated by rand() isn't that random... The higher order bits remained unchanged, and since this implementation uses them, the end result isn't quite what I expected.
Is there a more elegant, yet simple solution than to discard the first value or use remainders to achieve what I want?
Thanks a lot for your attention!
~Francisco
EDIT: Thank you all for your input. I had no idea rand() was such a sucky RNG :P
Given that rand() is not a very strong random number generator, the small amount of bias added by the standard approach is probably not an issue: (higher-lower) needs to be smaller than MAX_RAND of course.
lower + rand() % (higher-lower+1);
fixed off by one error.
rand() is not a good random-number generator. In addition to the problem you observed it's period length can be very short.
Consider using one of the gsl random number generators.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With