Random numbers#
Being able to generate random numbers is useful both for games and for computational techniques such as Monte Carlo methods.
Using the built-in random library#
The standard built-in random library which is part of the Python offers several useful functions:
random.randint(a, b) – random integer between a and b (inclusive)
random.random() – random float between 0.0 and 1.0
random.choice(seq) – random element from a sequence (typically a list)
random.shuffle(seq) – shuffle a list in-place (i.e. the list changes)
There are many other useful functions, see the full documentation for more information.
import random
ntries = 20
for i in range(ntries):
print(random.randint(1,10))
4
6
10
9
3
8
3
9
6
5
9
7
6
3
1
10
5
9
6
4
for i in range(ntries):
print(random.random())
0.6801894755686804
0.9094084191557079
0.8778989237796774
0.41144723463072563
0.40406117799697616
0.47482337203724945
0.7464046511319727
0.43319093725373137
0.8499297422602158
0.635046269898856
0.8367422048468426
0.677279670089847
0.35192814222375
0.2962411016873928
0.023720888050612343
0.467772937173183
0.12389269366357136
0.6245444719459522
0.9547784614389204
0.7382503515838159
l1 = ['rock','paper','scissors']
for i in range(ntries):
print(random.choice(l1))
paper
rock
scissors
rock
paper
paper
rock
rock
paper
scissors
rock
rock
paper
rock
paper
rock
rock
rock
paper
paper
l2 = [0,1,2,3,4,5,6,7,8,9]
nshuffles = 5
for i in range(nshuffles):
random.shuffle(l2) # Note that l2 is changed here
print(l2)
[0, 1, 5, 8, 6, 9, 4, 7, 2, 3]
[5, 2, 6, 4, 9, 7, 1, 3, 0, 8]
[4, 0, 6, 3, 5, 2, 1, 9, 7, 8]
[3, 6, 7, 4, 5, 8, 2, 1, 0, 9]
[4, 6, 8, 5, 1, 0, 3, 7, 9, 2]
Dungeons and Dragons dice#
d4 = lambda: random.randint(1,4)
d6 = lambda: random.randint(1,6)
d8 = lambda: random.randint(1,8)
d10 = lambda: random.randint(1,10)
d12 = lambda: random.randint(1,12)
d20 = lambda: random.randint(1,20)
d4()
3
d6()
5
d20()
3
Numpy and random numbers#
As a core package for numerical computation in Python, Numpy offers a variety of functionality for using random numbers. Often this is array-oriented (as opposed to single valued as in the built-in random module). Some examples of useful functions include:
np.random.random(size) - generate
size
random numbers uniformly in the range [0,1)np.random.randint(low,high,size) - generate
size
random integers uniformly in the range [low,high)np.random.normal(loc=0.0,scale=1.0,size=10) - generates
size
numbers from a normal/gaussian distribution centered atloc
with standard devitationscale
(note that use of the keywords is required)
See the full documentation for more possibilities.
import numpy as np
print(np.random.random(10))
[0.33220297 0.27094937 0.10991044 0.86823173 0.03204402 0.00451145
0.2395526 0.71103928 0.84242267 0.21892699]
print(np.random.randint(1,7,10))
[2 4 5 4 4 2 2 6 2 5]
print(np.random.normal(size=10))
[-0.00737491 -0.48210976 -1.42249881 -0.3881652 0.37479936 -0.60501388
0.22367986 0.28576499 -0.46607219 1.36660142]