Random Number Generation Problem

I take a programming course and we use C ++. We had a task where, at some point, we needed to encode a function that would return a random number in the [upper, lower] interval. I used the following:

lower + (int) (upper * (rand() / (RAND_MAX + 1.0)));

I did not forget to change srandusing srand((unsigned int) time(0)).

However, I get the same value every time! I asked my professor for help, and after some investigation it turned out that the first number generated rand()was not random ... Higher order bits remained unchanged, and since this implementation uses them, the end result isn "What I expected.

Is there a more elegant but simple solution than abandoning the first value or using leftovers to achieve what I want?

Thank you very much for your attention!

~ Francisco

EDIT: Thank you all for your input. I had no idea that I rand()was such a sucking RNG: P

+3
source share
5 answers

Given that rand () is not a very strong random number generator, a small offset added by the standard approach is probably not a problem: (higher) should be less than MAX_RAND, of course.

lower + rand() % (higher-lower+1);

fixed by one mistake.

+2
source

rand()is not a good random number generator. In addition to the problem you have observed, the length of the period can be very short.

gsl .

+1

random() rand(). , rand(). <stdlib.h> / man 3 random.

+1

,

lower + (int) upper * (rand() / (RAND_MAX + 1.0));

lower + (int) (upper - lower + 1)*(rand() / (RAND_MAX + 1.0));

:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define lower 10
#define upper 20

int main(void)
{
    int i;
    int number;

    srand(time(0));
    for(i=0; i<10; i++)
    {
        number = lower + (int) (upper - lower + 1)*(rand() / (RAND_MAX + 1.0));
        printf ("%d\n", number);
    }

    return 0;
}    

, time(0) , .

+1

++ 0x ( TR1 Boost), , rand. (random_device), , (mt19937), (, uniform_int min-max ).

, rand(), .

- , rand, .

+1

Source: https://habr.com/ru/post/1736375/


All Articles