Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Current implementation of rand() does not generate half of the numbers #2341

Closed
WheretIB opened this issue May 8, 2014 · 1 comment
Closed
Assignees

Comments

@WheretIB
Copy link

WheretIB commented May 8, 2014

In the current implementation, lowest two bits of the rand() result are always either 00/11 or 01/10 depending on the starting seed.

the following code produces an endless stream of either 0 3 0 3 0 3 0 3... or 1 2 1 2 1 2 1 2...:

srand(time(NULL));
while(1)
printf("%d\n", rand() % 4);

This happens because the multiplier does not follow the proper conditions of a good Linear congruential generator (rule #3 is violated):
http://en.wikipedia.org/wiki/Linear_congruential_generator#Period_length

@juj
Copy link
Collaborator

juj commented May 8, 2014

When I was studying LCGs from Knuth several years ago, I seem to have documented the following LCG configurations:

https://github.com/juj/MathGeoLib/blob/master/src/Algorithm/Random/LCG.cpp#L32

and then settled to using

https://github.com/juj/MathGeoLib/blob/master/src/Algorithm/Random/LCG.h#L69

i.e. a multiplier of 69621, increment 0, and modulus 0x7FFFFFFF, which was referred by Knuth as "Park and Miller generator nr. 3". Perhaps that would have a better randomness?

@juj juj self-assigned this Aug 26, 2014
@juj juj mentioned this issue Aug 26, 2014
@juj juj closed this as completed in 4a744fb Sep 15, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants