rand() %4000000000UL giving only small values
Asked Answered
D

4

6

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

On codepad.org it outputs large values like

378332591
1798482639
294846778
1727237195
62560192
1257661042

But on Windows 7 64bits, it outputs only small values (tested compiling on VS11 & Code::Blocks)

10989
13493
13169
18581
17972
29

Thanks in advance for helping a c++ learner ;)

Doublefaced answered 9/4, 2012 at 14:40 Comment(0)
B
9

rand() generates only numbers up to its RAND_MAX.

According to MSDN, on Windows RAND_MAX is just 32767, or (2**15 - 1) (note that this is the minimal allowed RAND_MAX according to C standard (here link to open group base spec, which is based on C standard)).

If you want bigger numbers, you need to call it more times and bitshift, e.g.:

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

(example on codepad).

Bend answered 9/4, 2012 at 14:44 Comment(0)
C
5

The behavior you're encountering is due to the values of RAND_MAX on the two systems you're testing on.

On the windows 7 system, RAND_MAX is 32767, a value significantly smaller than whatever environment codepad runs your code in. Because of this, the randomly generated values are in a significantly smaller range.

Cognizant answered 9/4, 2012 at 14:44 Comment(0)
T
4

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

You can create a bigger random number by pasting the output of two rand() calls.

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

You could also switch to a different random number generator such as Boost.Random or C++11.

Tricky answered 9/4, 2012 at 14:44 Comment(0)
M
2

the results of rand are implementation dependent and guaranteed to only be as high as 32767:

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

So when you run your code on different systems with different library implementations, you can get different results- Windows is only returning numbers up to 32767, so you get small numbers from your code.

Mass answered 9/4, 2012 at 14:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.