random模块和np.random模块的比较

1.random.random() 和 np.random.random()

随机生成 [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])

2.random.randint(a, b) 和 np.random.randint(a, b)

区别:生成 [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 "<stdin>", 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]])

3.random.uniform(a,b) 和 np.random.uniform(a,b)

生成 [a, b] 之间的浮点数

>>> random.uniform(1, 3)
1.0462425337392052
>>> np.random.uniform(1, 3)
1.7714958695125578

4.random.sample(s, k)

从指定序列中随机选择k个元素,返回一个列表


>>> random.sample([1,3,5,6], 3)
[5, 3, 6]

5.np.random.rand(a, b)

生成shape为(a, b)的 [0, 1)之间的浮点数

>>> np.random.rand(1, 3)
array([[0.26973298, 0.25983477, 0.8810986 ]])

6.random.shuffle(x)

将列表重新随机排列


>>> p = [1, 5, 3, 2, 8]
>>> random.shuffle(p)
>>> p
[3, 8, 5, 2, 1]

7. random.randrange(a, b, k)

生成一个在 [a, b] 之间且间隔为k的随机整数

>>> random.randrange(2, 9, 2)
6
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值