随机生成 [0,1)之间的浮点数
>>> import random
>>> random.random()
0.3880264733393649
>>> import numpy as np
>>>np.random.random()
0.7506845493192744
>>> np.random.random(2)
array([0.33454115, 0.72391058])
区别:生成 [a, b] 之间的整数,后一个生成 [a, b)
>>> random.randint(1, 2)
1
>>> random.randint(1, 2)
2
>>> np.random.randint(1, 1)
Traceback (most recent call last):
File "" , line 1, in <module>
File "mtrand.pyx", line 743, in numpy.random.mtrand.RandomState.randint
File "_bounded_integers.pyx", line 1346, in numpy.random._bounded_integers._rand_int32
ValueError: low >= high
>>> np.random.randint(1, 6, (2,3))
array([[3, 3, 5],
[2, 5, 5]])
生成 [a, b] 之间的浮点数
>>> random.uniform(1, 3)
1.0462425337392052
>>> np.random.uniform(1, 3)
1.7714958695125578
从指定序列中随机选择k个元素,返回一个列表
>>> random.sample([1,3,5,6], 3)
[5, 3, 6]
生成shape为(a, b)的 [0, 1)之间的浮点数
>>> np.random.rand(1, 3)
array([[0.26973298, 0.25983477, 0.8810986 ]])
将列表重新随机排列
>>> p = [1, 5, 3, 2, 8]
>>> random.shuffle(p)
>>> p
[3, 8, 5, 2, 1]
生成一个在 [a, b] 之间且间隔为k的随机整数
>>> random.randrange(2, 9, 2)
6