I need your help and please give me some advice. From programming pearls I know that to generate random 30 bit integer we should write it like this:
RAND_MAX*rand()+rand()
But what could I do for generating not 30, but 64 bit random integer instead? I think that is very inefficient method if I multiply two 30 bit integers and then multiply again 4 bit integer, so what kind of method should I use? I am using now popcount_1 different method for 64 bit one and I would like to test it on random integers(I am also measuring the time which each one takes to accomplish the task)
'Returns a pseudo-random integral value between 0 and RAND_MAX (0 and RAND_MAX included).' - http://en.cppreference.com/w/cpp/numeric/random/rand
So you should use RAND_MAX + 1 (it's like generating a number digit by digit and then converting it to base 10) instead of RAND_MAX. This way you can generate numbers with one, two, three etc. digits in base RAND_MAX + 1(possibly with leading zeroes) and convert them to base 10 and get arbitrarily large numbers.
Everything that you obtain larger than your desired MAX_VALUE can be discarded and you still get 1/(MAX_VALUE + 1) probability for obtaining each number.
Note, that this method might take a while, especially if your desired MAX_VALUE is a lot less than the maximum value that can be obtained before discarding the numbers that are not desired, as the expected number of steps to obtain a random number in [0, MAX_VALUE] with this algorithm is: (MAX_OBTAINABLE_VALUE + 1)/(MAX_VALUE + 1)
This could be a solution, without multiplication:
A random 64 bit int is essentially 64 random bits interpreted as an int.
Fill a byte array of length 8 with random bytes (see here for how) and interpret these as an int (see here for how).
A generic solution:
Use:
unsigned long long R = genrand<unsigned long long>();
.The
bits
counter keeps track of the number of bits still needed.First, I have my doubts about the solution you post for a 30 bit integer.
RAND_MAX
itself could be a 31 bit value, andRAND_MAX * rand() + rand()
is likely to overflow, producing undefined behavior (and in practice, negative values).If you need a value larger than the guaranteed minimum of
RAND_MAX
, or for that matter, anything that isn't significantly smaller thanRAND_MAX
, the only solution will be to use successive calls torand()
, and combine the values, but you need to do this carefully, and validate the results. (Most implementations ofrand()
use linear congruent generators, which while adequate for some tasks, aren't particularly good in this case.) Anyway, something like:(The code in
rand256
is designed to eliminate the otherwise unavoidable bias you get when mappingRAND_MAX
values to 256 values.)If boost is an option, you could use boost random.