Ticket #5280 (new bug)
System.Random commits (rand `mod` base) error.
|Reported by:||rrnewton||Owned by:||rrnewton|
|Keywords:||random mod base||Cc:|
|Type of failure:||Incorrect result at runtime||Difficulty:|
|Test Case:||Blocked By:|
You have probably at some point come across the C code "rand() % base"'. It is very intuitive, but unfortunately creates non-uniform random numbers, which is easy to see if you imagine rand() producing numbers in say [0,15) and base being 10.
In the function System.Random.randomIvalInteger you can see the same thing happening.
The only way I know how to deal with it and generate uniform integers within a range is to artificially restrict the range of the source of randomness to be a multiple of the desired base. It can be done simply by throwing out some random results.
This strategy appears to be used by GMP's mpz_urandomm function:
The file urandomm.c has the code.