python random和numpy random

本文介绍了Python标准库与NumPy库中生成随机整数的不同之处,Python的random.randint()函数返回的是闭区间的整数,而NumPy的同名函数返回的是半开区间的整数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

numpy是python的一个数值计算库,可是有许多语法和python不兼容。
比如python的random.randint(low,high)使用方法是返回[low,high]之间的整数,官方文档:

random.randint(a, b)
Return a random integer N such that a <= N <= b.
注意是两边都是闭区间,但在numpy中,random.randint(low,high)就变成了前闭后开,即不包含high,官方文档:
Return random integers from the “discrete uniform” distribution of the specified dtype in the “half-open” interval [low, high). If high is None (the default), then results are from [0, low).
所以在python和numpy一块用时,千万不能搞混,如果导入numpy建议起个别名:
import numpy as np;
这样当使用numpy的random时,可以:
np.random.randint(low,high)
使用python时,先导入random包:
import random as ra;
ra.randint(low,high);
这样就不易混了

参考:
python2.7文档:
https://docs.python.org/2.7/library/random.html?highlight=random#module-random
numpy文档:
https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.random.randint.html#numpy.random.randint

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值