The module RandomArray
defines a small number of very useful
functions. All allow the creation of arrays filled with random
numbers. It is a "front-end" to the functions provided by the
ranlib module.
As will all random-number generators, it's important to know how the
"seed" is set. The ranlib
random number generator uses two
integers to set its seed. So, you can, if you want, set the seed
with:
>>> RandomArray.seed(123,445)
where you could replace 123,445
with whatever seed pair you'd
like. Most of the time, however, one doesn't really care what the
seed is as long as it's different at each iteration. This is
done by calling the seed
function with no arguments (or with
both arguments set to 0
:
>>> RandomArray.seed()
If you wish to find out what the current seed is, the get_seed
routine returns a tuple of two integers:
>>> RandomArray.seed() >>> RandomArray.get_seed() (1325945862, 1011072672)
Be sure to initialize the random number generator before
calling get_seed
, or Python will abort!
The next function, random(shape=[])
takes a shape and returns
an array of the corresponding shape filled with random numbers chosen
from a uniform distribution between 0 and 1. If no argument is given,
then it returns a single random float.
>>> RandomArray.random() 0.353006571531 >>> RandomArray.random((5,5)) 0.15396087 0.56621116 0.82071984 0.32549462 0.34007969 0.89517653 0.33659944 0.28502297 0.50338095 0.77353072 0.02115688 0.0370131 0.29059708 0.08607747 0.74758685 0.35944587 0.20812804 0.07976629 0.14793196 0.70815533 0.3954463 0.76441997 0.6459406 0.47306126 0.85954911
The uniform(min, max, shape=[])
function also returns an array
of the given shape filled with random numbers, but it uses random
numbers chosen between the first two arguments. Thus
uniform(0.0,1.0,s)
is equivalent to random(s)
(and they
will given the same result if started with the same seed).
>>> RandomArray.uniform(1.0, 10.0, (5,5)) 5.47760731 1.02119061 9.31002319 7.77270436 4.48571435 4.9603433 8.21003532 1.23855919 2.37876996 1.76282863 9.39198828 3.76864266 5.41560912 7.62688446 2.59339081 7.59900343 4.01759726 8.9741956 6.65304196 5.26141241 3.62762499 2.26081848 4.96731195 5.32794487 7.43747491
The randint(min, max, shape=[])
call is just like
uniform
, except that it returns an array of integers
between the min and max values, and of the appropriate shape:
>>> RandomArray.randint(10) 6 >>> RandomArray.randint(10) 1 >>> RandomArray.randint(10) 4 >>> RandomArray.randint(100,200) 154 >>> RandomArray.randint(100,200) 190 >>> RandomArray.randint(100,200) 138 >>> RandomArray.randint(100,200) 113 >>> RandomArray.randint(100,200) 172 >>> RandomArray.randint(100,200, (5,5)) 150 150 189 146 159 188 148 176 100 155 196 188 122 176 117 174 124 170 138 143 156 137 148 110 113
Finally, the permutation(n)
function returns a random
permutation of the values in arrayrange(n). Thus:
>>> permutation(10) 6 4 5 7 0 2 9 3 8 1 >>> permutation((5,5)) 4 0 3 1 2 1 2 3 4 0 3 2 1 0 4 0 3 1 4 2 4 1 0 3 2