Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c++ rand() insignificant change

I ran into an issue when trying to generate random numbers where it outputs an ascending sequence of numbers with increments of 3 every second. I am using mingw g++ 6.3.0 with the following compiler flags: -std=c++11 -Wall.

As an example, after running the following code and running the executable multiple times it provides the following output below:

main.cpp:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <iostream>
#include <cstdlib>
#include <ctime>

int main() {
  std::srand(std::time(0));

  int rnd = std::rand();
  std::cout << rnd << '\n';

  return 0;
}

Console output:

C:\...>make
g++ main.cpp -std=c++11 -Wall    -o a.exe

C:\...>a
21154

C:\...>a
21157

C:\...>a
21157

C:\...>a
21157

C:\...>a
21160

C:\...>a
21160

C:\...>a
21163

C:\...>a
21163

>Solution :

Well, rand() will return the same sequence of numbers for a given seed, which is why you see the change every second (you’re seeding it with the time in seconds).

As for incrementing by 3 each time, std::rand is not guaranteed to produce sequences of any particular quality, and yours appears particularly not-that-great (not uncommon for rand). There are better quality generators in <random> (see docs here).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading