Why does C++ rand() seem to generate only numbers of the same order of magnitude?

前端 未结 9 2068
孤独总比滥情好
孤独总比滥情好 2021-01-30 01:14

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

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-30 02:02

    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):

    enter image description here

提交回复
热议问题