随机数在编程中非常重要,有些场合不得不使用随机数,如创建1000个满足0~1正太分布的随机数;有些场合可以避开使用随机数,但人为设置的数字显得呆板,最后还是选择随机数。
1、创建1000个满足0~1正太分布的随机数,代码如下:
import numpy as np
from matplotlib import pyplot as plt
avg = 0
std = 1
num = 1000
np.random.seed(0)
# bins指的是柱子的数目
plt.hist(np.random.normal(avg, std, num), color='b', label='0-1 Normal Distribution', bins=100)
plt.title('0-1 Normal Distribution')
plt.xlabel('x', fontsize=12)
plt.ylabel('y', fontsize=12)
plt.show()
运行结果:
2、利用随机数为不同类别的矩形框设置不同的颜色,代码如下:
import numpy as np
classes = ['气孔', '夹渣', '焊瘤', '裂纹', '咬边']
rgbs = []
for i in range(len(classes)):
# 即使以后增加类别,之前创建的类别的矩形框的颜色也不会变
np.random.seed(i)
rgb = [np.random.randint(0,255) for i in range(3)]
rgbs.append(rgb)
print(rgbs)
3、numpy创建随机数方法总结
import numpy as np
# 在[low,high)范围内生成随机的浮点数
print('np.random.uniform(0,100,3) is\n', np.random.uniform(0,100,3),'\n')
# 在[0,1)范围内生成随机的浮点数
print('np.random.random(3) is\n', np.random.random(3),'\n')
# 生成满足(avg, std)分布的随机的浮点数
print('np.random.normal(10, 1, (2,3)) is\n', np.random.normal(10, 1, (2,3)),'\n')
# 生成满足(0,1)分布的随机的浮点数
print('np.random.randn(2,3) is\n', np.random.randn(2,3),'\n')
# 在[low,high)范围内生成随机的整数
print('np.random.randint(0,100,3) is\n', np.random.randint(0,100,3),'\n')
# 从list中随机抽取数据
print('np.random.choice([1,2,3,4,5,6], 3) is\n', np.random.choice([1,2,3,4,5,6], 3),'\n')
# 将list随机打乱
data = [1,2,3,4,5,6]
np.random.shuffle(data)
print('data = np.array([1,2,3,4,5,6]);np.random.shuffle(data) is\n', data)
运行结果:
4、random创建随机数方法总结
import random
# 从列表中不重复地随机抽取若干个元素
print('random.sample([1,2,3,4,5,6],3) is\n', random.sample([1,2,3,4,5,6],3), '\n')
# 将列表顺序打乱
list = [1,2,'a','b']
random.shuffle(list)
print("random.shuffle([1,2,'a','b']) is\n",list)
运行结果: