In a small application written in C/C++, I am facing a problem with the rand
function and maybe the seed :
I want to produce a sequence of random numbers th
The basic (and correct) answer was already given and accepted above: there are 10 numbers between 0 and 9, 90 numbers between 10 and 99, 900 between 100 and 999, etc.
For a computationally efficient way to get a distribution with approximately logarithmic distribution, you want to right-shift your random number by a random number:
s = rand() & 31; // a random number between 0 and 31 inclusive, assuming RAND_MAX = 2^32-1
r = rand() >> s; // right shift
It's not perfect, but it's much faster than computing pow(2, rand()*scalefactor)
. It will be "lumpy" in the sense that the distribution will be uniform for numbers within a factor 2 (uniform for 128 to 255, half the density for 256 to 1023, etc).
Here is a histogram of the frequency of the numbers 0 to 31 (in 1M samples):