1

I'm trying to generate a random number using rand() command, but each time i get very similar numbers. This is my code:

#include <iostream> #include <time.h> using namespace std; int main() { srand(time(0)); cout << rand(); return 0; } 

I ran it 5 times and the numbers i got are: 21767 21806 21836 21862 21888

How can i make the numbers be more different?

4
  • Terrible random number generator, especially on MS platforms. Use the amazing offerings of <random> instead. And fyi, if you did use rand and srand you should #include <cstdlib>, as the standard library mandates that header for access to those functions. Commented Mar 29, 2021 at 7:47
  • 1
    In other words, you want your random numbers to be less random? Commented Mar 29, 2021 at 7:47
  • time() has seconds precision, so if those 5 runs are close together, you will be seeding the RNG with very similar starting values. You should not be using the C rand() RNG in C++ to begin with, use C++ RNGs from the <random> library instead. Commented Mar 29, 2021 at 7:47
  • i want the numbers be more different and not so close each other Commented Mar 29, 2021 at 7:49

1 Answer 1

6

From the documentation of rand:

There are no guarantees as to the quality of the random sequence produced. In the past, some implementations of rand() have had serious shortcomings in the randomness, distribution and period of the sequence produced (in one well-known example, the low-order bit simply alternated between 1 and 0 between calls). rand() is not recommended for serious random-number generation needs. It is recommended to use C++11's random number generation facilities to replace rand().

It (and I) recommend to use the newer c++11 random number generators in <random>.

In your specific case it seems you want a std::uniform_int_distribution. An example, as given on the linked page is:

std::random_device rd; //Will be used to obtain a seed for the random number engine std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd() std::uniform_int_distribution<> distrib(1, RAND_MAX); std::cout << distrib(gen) << '\n'; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.