python中random.randint(1,100)随机数中包不包括1和100
在python中的random.randint(a,b)用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b。
print random.randint(12, 20) #生成的随机数n: 12 <= n <= 20
print random.randint(20, 20) #结果永远是20
#print random.randint(20, 10) #该语句是错误的。下限必须小于上限
所以说,random.randint(1,100)随机数中使包括1和100的。
其实通过查看该函数的python源码也能了解到具体的取值范围:
def randint(self, a, b):
"""Return random integer in range [a, b], including both end points.
"""
return self.randrange(a, b+1)
在源码中,其实randint最终调用的是randrange函数,randrange函数在随机是不包括上限数的。
看前面没怎么答全,总结一下:
对random模块,random.randint()是前闭后闭;即: random.randint(1,100)包含两端。
而对numpy模块,np.random.randint()是前闭后开;即:np.random.randint(1,100)只含1不含100(np类源于numpy即: from numpy import np)
你可以看一下 random.randint() 的源码
def randint(self, a, b):
"""Return random integer in range [a, b], including both end points.
"""
return self.randrange(a, b+1)
Return random integer in range [a, b], including both end points.
返回在 [a, b] 区间的随机数,包括 a, b
谢谢
包括,区间是两端封闭的。
random.randint(a, b)
Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).
摘自Python官网网页链接
numpy.random.randint(low, high=None, size=None, dtype='l')¶
Return random integers from low (inclusive) to high (exclusive).
Return random integers from the “discrete uniform” distribution of
the specified dtype in the “half-open” interval [low, high). Ifhigh is None (the default), then results are from [0, low).官方给出的解释应该是包括1不包括100
网页链接具体请看链接