c++ – The rand function in a loop

Question:

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

I call the function above in a loop, I need to make 1600 * 50000 scrolls. Everyone is familiar with the time() function, the loop runs many times more steps than 1 per second. As a result, I get bothersome identical numbers.

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

Answer:

srand(time(0)); needs to be called once at the beginning. Randomness will be normal. Calling srand all the time doesn't improve randomness.

Addition

If we simplify these two functions very much (very much), then the code will look something like this:

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. Making a fast and high-quality generator is quite difficult. Therefore, they take the simplest options. It makes no sense to complicate such generators – this will not improve their quality, at best it will remain the same. But it usually only gets worse.

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

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

  • buy a special device that will generate random numbers. For example, such a USB token "iBank 2 Key" . First thing I found on google 🙂
  • assemble such a device yourself – an article on Habré . There are many interesting things.
  • buy a special file with random numbers (yes, they sell this. I understand that many Linux lovers will say that I will generate /dev/random myself, but the companies promise good quality.
Scroll to Top