Rand ()% 4,000,000,000UL gives only small values

I have a question about the following code:

#include <iostream> #include <ctime> int main(){ unsigned long int blob; srand(time(0)); for(int counter = 0; counter <= 100; counter++) { blob = rand() % 4000000000UL ; std::cout << blob << std::endl; }//for system("pause"); return 0; } //main 

Large values ​​are displayed on codepad.org, for example

 378332591 1798482639 294846778 1727237195 62560192 1257661042 

But on Windows 7 64bits, it only displays small values ​​(tested compilation on VS11 and Code :: Blocks)

 10989 13493 13169 18581 17972 29 

Thanks in advance for helping the C ++ student;)

+6
source share
4 answers

rand () only generates numbers up to RAND_MAX.

According to MSDN , on Windows RAND_MAX is only 32767 or (2 ** 15 - 1) (note that this is the minimum allowable RAND_MAX in accordance with the C standard (here is a link to the group’s open base specification , which is based on the C standard)).

If you need large numbers, you need to call it more times and a bit-break, for example:

 long long int my_big_random = rand() ^ (rand() << 15) ^ ((long long int) rand() << 30); 

( example in the code ).

+9
source

The behavior you encounter is related to the RAND_MAX values ​​for the two systems you are testing.

On windows 7 RAND_MAX - 32767, a value significantly less than any environment code code runs your code. Because of this, randomly generated values ​​are in a much smaller range.

+5
source

Windows uses a random number generator with a maximum value of 32767. See the value for RAND_MAX.

You can create a larger random number by inserting the output of two calls to rand ().

 big_rand = rand() << 15 | rand(); 

You can also switch to another random number generator like Boost.Random or C ++ 11 .

+4
source

rand results are implementation dependent and are only guaranteed up to 32767:

http://en.cppreference.com/w/cpp/numeric/random/RAND_MAX

Therefore, when you run your code on different systems with different library implementations, you can get different results: Windows returns only numbers up to 32767, so you get small numbers from your code.

+2
source

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


All Articles