Why 1103515245 is used in rand?

前端 未结 4 1993
闹比i
闹比i 2020-12-13 04:29

I\'m talking about this surprisingly simple implementation of rand() from the C standard:

static unsigned long int next = 1;

int rand(void)           


        
4条回答
  •  生来不讨喜
    2020-12-13 04:58

    Remember that rand() is an approximation of a uniform distribution. Those numbers are used because they have been tested to show that they generate a more uniform-looking distribution.

    Given the multitude of pairs of unsigned integers in the representable range, I doubt anyone has tried them all with all valid seeds. If you think you have a better choice of parameters, just try it out! You have the code, just factor out the parameters of the LCG and run tests. Generate a bunch of numbers (say 10 million), compute a histogram of the generated numbers and plot that to look at the distribution.

    edit If you are interested in developing a pseudo-random number generator for use in real applications, I recommend that you read up on the considerable literature on the subject. The "advice" given above is only suggested to help show that choosing arbitrary "bigger, cool-looking and easier to remember" LCG parameters will give a very poor distribution. /edit

    Besides, it's a library function and I've never seen a program using the standard library version of rand() to remember its LCG's parameters.

提交回复
热议问题