Random and whrandom

Tim Peters tim.one at home.com
Sat Jan 20 23:46:11 EST 2001


[bogus at bogus.net]
> The whrandom algorithm may not generate very good random numbers. I
> created a pair of dice objects and rolled them 10,000 times, there
> seems to be a bias against rolling the same number on both dice.

Don't spread rumors without basis.  "bias" is both objectively demonstrable
and quantifiable if it is indeed there.  Run this and check the output
against a table of chi-squared values:

def chi_sq(seen, expected):
    n = len(seen)
    if n != len(expected):
        raise ValueError("len(seen) != len(expected)")
    sum = 0.0
    for i in range(n):
        e = float(expected[i])
        sum += (seen[i] - e)**2 / e
    return sum

def roll_the_dice(numtimes, verbose=0):
    from random import randint
    count = {}
    for i in range(1, 7):
        for j in range(1, 7):
            count[i, j] = 0
    for i in xrange(numtimes):
        pair = randint(1, 6), randint(1, 6)
        count[pair] += 1
    if verbose:
        all = count.items()
        all.sort()
        for pair, n in all:
            print pair, n
    # Just compute chi-squared for the duplicates.
    return chi_sq([count[i, i] for i in range(1, 7)],
                  [numtimes / 36.] * 6)

for i in range(20):
    x = roll_the_dice(10000, i == 0)
    print "chisq =", x

Short course is that I don't get "suspicious" results any more often than I
*should* get by chance.  Note that if you were guessing by eyeball, *people*
are notoriously poor judges of randomness.  Heck, if you asked me to pick a
number at random, and I answered 42, you'd probably think that wasn't random
either <wink>.





More information about the Python-list mailing list