Generating Random Numbers

The random() function returns the next random floating point value from the generated sequence. All of the return values fall within the range 0 <= n < 1.0.


In [1]:
import random
for i in range(5):
    print('%04.3f' % random.random(), end=' ')
print()


0.112 0.965 0.453 0.512 0.334 

In [2]:
import random
for i in range(5):
    print('{:04.3f}'.format(random.uniform(1, 100)), end=' ')
print()


15.681 75.444 95.950 6.651 57.688 

Seeding


In [3]:
import random

random.seed(1)

for i in range(5):
    print('{:04.3f}'.format(random.random()), end=' ')
print()


0.134 0.847 0.764 0.255 0.495 

In [4]:
import random

random.seed(1)

for i in range(5):
    print('{:04.3f}'.format(random.random()), end=' ')
print()


0.134 0.847 0.764 0.255 0.495 

In [5]:
import random
import os
import pickle

if os.path.exists('state.dat'):
    # Restore the previously saved state
    print('Found state.dat, initializing random module')
    with open('state.dat', 'rb') as f:
        state = pickle.load(f)
    random.setstate(state)
else:
    # Use a well-known start state
    print('No state.dat, seeding')
    random.seed(1)

# Produce random values
for i in range(3):
    print('{:04.3f}'.format(random.random()), end=' ')
print()

# Save state for next time
with open('state.dat', 'wb') as f:
    pickle.dump(random.getstate(), f)

# Produce more random values
print('\nAfter saving state:')
for i in range(3):
    print('{:04.3f}'.format(random.random()), end=' ')
print()


No state.dat, seeding
0.134 0.847 0.764 

After saving state:
0.255 0.495 0.449 

Random Integer


In [7]:
import random
print('[1, 100]:', end=' ')
for i in range(3):
    print(random.randint(1, 100), end=' ')
print('\n[-5, 5]', end=' ')
for i in range(3):
    print(random.randint(-5, 5), end=' ')
print()


[1, 100]: 50 56 78 
[-5, 5] -5 2 -1 

In [8]:
import random

for i in range(3):
    print(random.randrange(0, 101, 5), end=' ')
print()


35 90 15 

Picking Random Items


In [9]:
import random
import itertools

outcomes = {
    'heads': 0,
    'tails': 0,
}
sides = list(outcomes.keys())

for i in range(10000):
    outcomes[random.choice(sides)] += 1

print('Heads:', outcomes['heads'])
print('Tails:', outcomes['tails'])


Heads: 5058
Tails: 4942

Sampling


In [12]:
import random

with open('random.ipynb', 'rt') as f:
    words = f.readlines()
words = [w.rstrip() for w in words]

for w in random.sample(words, 5):
    print(w)


    "collapsed": false
    "    outcomes[random.choice(sides)] += 1\n",
    "        state = pickle.load(f)\n",
   "cell_type": "markdown",
    "print()"

SystemRandom


In [13]:
import random
import time

print('Default initializiation:\n')

r1 = random.SystemRandom()
r2 = random.SystemRandom()

for i in range(3):
    print('{:04.3f}  {:04.3f}'.format(r1.random(), r2.random()))

print('\nSame seed:\n')

seed = time.time()
r1 = random.SystemRandom(seed)
r2 = random.SystemRandom(seed)

for i in range(3):
    print('{:04.3f}  {:04.3f}'.format(r1.random(), r2.random()))


Default initializiation:

0.363  0.896
0.855  0.348
0.538  0.539

Same seed:

0.905  0.900
0.754  0.497
0.841  0.172