generate random digits with length of 5
bearophileHUGS at lycos.com
bearophileHUGS at lycos.com
Mon Sep 29 00:19:21 CEST 2008
Tim Chase:
> I suspect that the zfill responses don't have the property of equally
> distributed "randomness", as the first digit may more likely be a zero.
This code I have shown before:
str(randrange(100000)).zfill(5)
If the numbers are equally distributed in [0, 99999], then the leading
zeros have the correct distribution.
A little test program for you:
from string import digits
from random import choice, randrange
from collections import defaultdict
def main():
N = 1000000
freqs1 = defaultdict(int)
for i in xrange(N):
n = "".join(choice(digits) for d in xrange(5))
freqs1[n[0]] += 1
print [freqs1[str(i)] for i in xrange(10)]
freqs2 = defaultdict(int)
for i in xrange(N):
n = str(randrange(100000)).zfill(5)
freqs2[n[0]] += 1
print [freqs2[str(i)] for i in xrange(10)]
import psyco; psyco.full()
main()
The output:
[100153, 99561, 99683, 100297, 99938, 100162, 99738, 100379, 100398,
99691]
[99734, 100153, 100091, 100683, 99580, 99676, 99671, 100131, 100102,
100179]
Of course with a bit of math you can also demonstrate it :-)
Bye,
bearophile
More information about the Python-list
mailing list