Fork me on GitHub

Python标准库——random

python3 标准库学习记录——random生成伪随机数

In [4]:
print('hello,python3')
hello,python3

random()

函数从所生成的随机序列返回下一个随机的浮点数值,返回值在[0,1)区间

In [5]:
import random

for i in range(5):
    print('%04.3f' % random.random(), end=' ')
0.449 0.652 0.789 0.094 0.028 

uniform()

生成指定数值区间内伪随机数
实际执行:min + (max-min) * random()

In [6]:
for i in range(5):
    print('{:04.3f}'.format(random.uniform(1,100)), end=' ')
83.741 43.844 76.466 1.208 45.093 

seed()

指定种子

In [7]:
random.seed(1)

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

getstate()保存状态

getstate()会返回一些值,以后可以用setstate()恢复这些数据重新初始化随机数生成器。

保存随机算法内部状态,用来控制后续各轮的随机数,继续生成随机数前恢复到前一个状态,这减少由之前输入得到重复的值或值序列的可能性。

In [8]:
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 

randint()

randint()参数的值是随机数区间两端,第一个值要小于第二个值

In [9]:
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=' ')
[1,100]: 84 49 27 
[-5, 5] -4 2 -5 

randrange()

从区间选择值的更一般形式,更高效,并不真正构造区间
randrange(start,stop,step)等价从range(start,stop,step)中随机选择一个值

In [10]:
for i in range(3):
    print(random.randrange(0, 100, 5), end=' ')
60 65 95 

choice()

在一个序列中随机选择一个元素

In [11]:
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: 4942
Tails: 5058

shuffle()

shuffle()洗牌,避免将一张牌发出去两次

In [12]:
import random
import itertools

FACE_CARDS = ('J', 'Q', 'K', 'A')
SUITS = ('H', 'D', 'C', 'S')


def new_deck():
    return [
        # Always use 2 places for the value, so the strings
        # are a consistent width.
        '{:>2}{}'.format(*c)
        for c in itertools.product(
            itertools.chain(range(2, 11), FACE_CARDS),
            SUITS,
        )
    ]


def show_deck(deck):
    p_deck = deck[:]
    while p_deck:
        row = p_deck[:13]
        p_deck = p_deck[13:]
        for j in row:
            print(j, end=' ')
        print()
        
# Make a new deck, with the cards in order
deck = new_deck()
print('Initial deck:')
show_deck(deck)

# Shuffle the deck to randomize the order
random.shuffle(deck)
print('\nShuffled deck:')
show_deck(deck)

# Deal 4 hands of 5 cards each
hands = [[], [], [], []]

for i in range(5):
    for h in hands:
        h.append(deck.pop())

# Show the hands
print('\nHands:')
for n, h in enumerate(hands):
    print('{}:'.format(n + 1), end=' ')
    for c in h:
        print(c, end=' ')
    print()

# Show the remaining deck
print('\nRemaining deck:')
show_deck(deck)
Initial deck:
 2H  2D  2C  2S  3H  3D  3C  3S  4H  4D  4C  4S  5H 
 5D  5C  5S  6H  6D  6C  6S  7H  7D  7C  7S  8H  8D 
 8C  8S  9H  9D  9C  9S 10H 10D 10C 10S  JH  JD  JC 
 JS  QH  QD  QC  QS  KH  KD  KC  KS  AH  AD  AC  AS 

Shuffled deck:
 2D  8H  4H  8D  AC  AH  QC  JC  5S  4C  3C  9D  KH 
 8S  AD  7C  QD  7H  JH  JD  KC  7D  JS  7S  2S  4S 
 2H  KS  3S  9C  5D  6D  9S  9H  KD 10H  6H  3H 10D 
 3D  6C  5C 10S 10C  AS  6S  QS  8C  5H  4D  2C  QH 

Hands:
1:  QH  8C 10C  3D 10H 
2:  2C  QS 10S 10D  KD 
3:  4D  6S  5C  3H  9H 
4:  5H  AS  6C  6H  9S 

Remaining deck:
 2D  8H  4H  8D  AC  AH  QC  JC  5S  4C  3C  9D  KH 
 8S  AD  7C  QD  7H  JH  JD  KC  7D  JS  7S  2S  4S 
 2H  KS  3S  9C  5D  6D 

sample()

采样,可以从大量样本中获得随机样本,sample函数可以生成无重复值的样本,且不会修改输入序列。

多个并发生成器

random还包括一个Random类,可以生成Random实例,各个实例单独初始化和使用,不会和其他实例返回的值相互干扰

非均匀分布

  • 正态分布 normalvariate() gauss()
  • 指数分布 expovariate()
  • 近似分布
  • 角分布

Comments