double rnd() { srand(time(0)); return(rand() % 1000 / 1000.0); } 

I call the function above in a loop, I need to complete 1600 * 50,000 scrolls. Everyone is familiar with the time() function, the cycle in a second runs many times more steps than 1. As a result, I get bothering the same numbers.

To solve my problem, I need to get a random number (probability) of an event on each scrolling.

    2 answers 2

    srand(time(0)); need to be called once at the beginning. Accident will be normal. Challenge srand randomness does not improve.

    Addition

    If you greatly simplify these two functions (very strongly), then the code will look like this somewhere:

     int seed = 0; // это начальное значение генератора int gen = 0; // начальное значения рандома int magick = 1234567; // это такая специальная магическая константа, я ее сам придумал:) // а вообще то есть целые исследования, которые определяют правильные константы // того же Кнута почитать можно void srand(int s) { seed = s; } int rand() { return func(gen, seed); } int func(int g, int s) { // эта функция на базе предыдущего значения вычисляет новое. // главное, что нужно понимать, что при одних и тех же значениях аргументов, // результат будет один и тот же. // реализация, приведенная ниже - это один с возможных вариантов. return (s * magick + g) % 0xFFFFFFFF; } 

    The question arises - why is this done? Everything is very simple. Make a fast and high-quality generator is quite difficult. Therefore, take the most simple options. It makes no sense to complicate such generators - this will not improve their quality; at best, it will remain the same. But usually it only gets worse.

    Another reason this is done is the convenience of debugging. After all, seed determines the entire sequence. And if you set it the same, then rand will output the same sequence.

    If you really need a random sequence, then there are the following options:

    • buy a special device that will generate random numbers. Here, for example, is a USB token "iBank 2 Key" . The first thing that was found in Google :)
    • assemble such a device yourself - an article on Habré . There are many interesting things.
    • buy a special file with random numbers (yes, this is a sale. I understand that many Linux lovers will say, they say, I will get rid of it with /dev/random , but companies promise good quality.
    • It helped, everything was so simple or something. It turns out the opposite: a frequent call spoils randomness? - adrug
    • @Adrug, the srand call sets the first number in the chain of pseudo-random numbers, and it depends only on the input argument srand. Therefore, calling rand () after calling srand (x) will return the same number if x is fixed. - dzhioev

    This is the so-called. "frequent error".

    If the program code contains multiple attempts to "restart" a pseudo-random number generator, using as a seed value the current time value obtained by calling time(NULL)

     ... srand(time(NULL)); ... 

    it may happen that such calls to srand will follow each other very quickly. So fast, that time(NULL) will return the same time value. This will lead to the fact that the pseudo-random number generator will constantly restart with the indication of the same seed value. As a result, subsequent rand() calls will produce the same pseudo-random sequence.

    For example, the following code, being executed, will most likely output the same pseudo-random sequence two times.

     #include <stdlib.h> #include <stdio.h> #include <time.h> int main() { srand(time(NULL)); for (unsigned n = 20; n > 0; --n) printf("%d ", rand()); printf("\n"); srand(time(NULL)); for (unsigned n = 20; n > 0; --n) printf("%d ", rand()); printf("\n"); } 

    This problem is also sometimes reported in the following form: "Under the debugger I have different random numbers in my program, and without the debugger, the same ones." Indeed, when the program is executed step-by-step in an interactive debugger, it runs “slowly” and between calls to the srand time value time(NULL) time to change, which creates the illusion that everything works “as intended”. But it is worth running the program into free execution, as the problem manifests itself in all its glory.

    If you need a srand(time(NULL)) call in your program, in most cases it is enough to do it only once at the start of the program.