0

I am trying to digest a very common method to generate random number in smaller range using a random number generator of larger range.

let say in C/C++ i am using rand() [it generate random number between 0 to RAND_MAX RAND_MAX is atleast 32767.]

let say i have to generate random number between 0-99 both inclusive. a common trick done is rand()%100.

Wont rand()%100 generate slightly different probablity [slightly higher for 0-67]

what is the best way to do this so that you generate uniform random number?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
David
  • 4,634
  • 7
  • 35
  • 42
  • `return (double)rand() / (double)RAND_MAX * (double)N ;` – dawg Dec 09 '19 at 01:26
  • `rand()%100` is the best way! How did you get that probability? – bli07 Dec 09 '19 at 01:45
  • Your concern about the simple modulo computation is entirely warranted. For a correct and fast approach, see: Daniel Lemire, "Fast Random Integer Generation in an Interval." *ACM Transactions on Modeling and Computer Simulation*, Vol. 29, No. 1, Feb. 2019, article 3. Draft is available from [ArXiv](https://arxiv.org/abs/1805.10941) – njuffa Dec 09 '19 at 01:51
  • 4
    No, @brandon, it isn't. See, for example, https://stackoverflow.com/q/10984974/56778 – Jim Mischel Dec 09 '19 at 04:08
  • No way can be better than `rand()%100`. The reason that you get different probability is you are testing with too small numbers. And it's still pseudorandom. – bli07 Dec 09 '19 at 16:11
  • @brandon You can easily test this with a simple program that demonstrates the bias. Create an array of 100 integers. Then generate 1 million random numbers using the `rand() % 100` method. As you generate each number, increment its corresponding count. Then compare the counts. If there is no bias, then all numbers should occur pretty much with the same frequency. If there is bias, then there will be two ranges of numbers, with one range occurring much more frequently than the other. – Jim Mischel Dec 18 '19 at 21:11

0 Answers0