Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A problem with random number generation

Tags:

c++

random

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

like image 334
F. P. Avatar asked Jan 23 '26 04:01

F. P.


2 Answers

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.

like image 93
Chris Becke Avatar answered Jan 25 '26 17:01

Chris Becke


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.

like image 26
Benjamin Bannier Avatar answered Jan 25 '26 19:01

Benjamin Bannier