3
$\begingroup$

I'm trying to create a random 6 digit code. If I generate a random number between 0 and 999999 and then pad it with zeros to make it 6 digits is it random or is it biased in some way?

E.g It generates 750 so it is then padded to 000750 It generates 28149 so it is padded to 028149

Does this achieve the same as generating a random integer between 0 and 9 six times and then putting the numbers together in a string?

Thanks.

  • 0
    @Rahul: http://dilbert.com/strip/2001-10-252015-08-06

2 Answers 2

2

It makes no difference, provided that in both cases you’re generating the numbers with uniform distribution. Consider, for instance, the probability of generating a number that starts with at least three zeroes. The first method gives you $1000$ such numbers out of $1,000,000$ possibilities, so the probability of getting one is $\frac{1000}{1,000,000}=\frac1{1000}$. In the second method you must generate three zeroes in succession to start, after which you don’t care: the probability of that is $\left(\frac1{10}\right)^3=\frac1{1000}$.

More generally, each of the $10^6$ possible six-digit numbers has one chance in a million of being generated under either scheme.

1

The two procedures should both yield "random" strings of $6$ digits, with all strings equally likely. There may be subtle differences, since we are using pseudo-random number generators.