jeudi 30 septembre 2021

What is the best way of generating a random value within a closed interval in C?

In general, when I need to generate a random value within a closed interval (considering B as the beginning and E as the end of the interval) in C, I use one of the following approaches:

Approach 1:

n = round(B + ( (float)rand() / RAND_MAX ) * (E - B));

Approach 2:

n = B + rand()%(E - B+1);

Both of them consider the initialization of the random seed with the function time():

srand(time(NULL));

In Linux systems, both approaches seem good enough for generating interesting random values. However, in Windows systems, sometimes the numbers do not appear to be random enough.

Investigating these systems, I've found that the value of RAND_MAX is different. In the Linux systems that I have tested RAND_MAX is 2147483647. In these windows systems with a not-so-good behavior, RAND_MAX is 32767.

I think that with a larger RAND_MAX value we can generate better random numbers. But I'm not sure.

With this in mind, my question is: Is there some good way of generating interesting random numbers (within a closed interval) that work well on all systems?

Besides that, my approaches 1 and 2 are good approaches for generating random numbers within a closed interval?




Aucun commentaire:

Enregistrer un commentaire