Python 随机 randint 和 randrange 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3540431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between random randint and randrange?
提问by killown
The only difference that I know between randrangeand randintis that
randrange([start], stop[, step])you can use the step and random.randrange(0, 1)will not consider the last item, while randint(0, 1)returns a choice inclusive of the last item.
我知道randrange和之间的唯一区别randint是
randrange([start], stop[, step])您可以使用该步骤并且random.randrange(0, 1)不会考虑最后一项,而randint(0, 1)返回包含最后一项的选择。
So, I can't find a reason for explain why randrange(0, 1)doesn't return 0 or 1, why exist randint(0, 1)and randrange(0, 2)instead of a randrange(0, 1)who returns 0 or 1?
所以,我找不到解释为什么randrange(0, 1)不返回 0 或 1,为什么存在randint(0, 1)而randrange(0, 2)不是randrange(0, 1)返回 0 或 1 的原因?
采纳答案by killown
The docs on randrangesay:
上的文档randrange说:
random.randrange([start], stop[, step])Return a randomly selected element from
range(start, stop, step). This is equivalent tochoice(range(start, stop, step)), but doesn't actually build a range object.
random.randrange([start], stop[, step])从 中返回一个随机选择的元素
range(start, stop, step)。这等效于choice(range(start, stop, step)),但实际上并不构建范围对象。
And range(start, stop)returns [start, start+step, ..., stop-1], not [start, start+step, ..., stop]. As for why... zero-based counting rules and range(n)should return nelements, I suppose. Most useful for getting a random index, I suppose.
并range(start, stop)返回[start, start+step, ..., stop-1],不是[start, start+step, ..., stop]。至于为什么......我想是基于零的计数规则并且range(n)应该返回n元素。我想对于获取随机索引最有用。
While randintis documented as:
虽然randint记录为:
random.randint(a, b)Return a random integer N such that
a <= N <= b. Alias forrandrange(a, b+1)
random.randint(a, b)返回一个随机整数 N 使得
a <= N <= b。别名randrange(a, b+1)
So randintis for when you have the maximum and minimum value for the random number you want.
randint当您拥有所需随机数的最大值和最小值时也是如此。
回答by Veedrac
https://github.com/python/cpython/blob/.../Lib/random.py#L218
https://github.com/python/cpython/blob/.../Lib/random.py#L218
def randint(self, a, b):
"""Return random integer in range [a, b], including both end points.
"""
return self.randrange(a, b+1)
回答by user1
The difference between the two of them is that randintcan only be used when you know both interval limits.
If you only know the first limit of the interval randintwill return an error. In this case you can use randrangewith only one interval and it will work.
Try run the following code for filling the screen with random triangles:
两者的区别在于,randint只有当您知道两个区间限制时才能使用。如果只知道区间的第一个限制randint会返回错误。在这种情况下,您只能使用randrange一个间隔,它会起作用。尝试运行以下代码,用随机三角形填充屏幕:
import random
from tkinter import *
tk = Tk()
canvas = Canvas(tk, width=400, height=400)
canvas.pack()
def random_triangle(l1,l2,l3,l4,l5,l6):
x1 = random.randrange(l1)
y1 = random.randrange(l2)
x2 = x1 + random.randrange(l3)
y2 = y1 + random.randrange(l4)
x3 = x2 + random.randrange(l5)
y3 = y2 + random.randrange(l6)
canvas.create_polygon(x1,y1,x2,y2,x3,y3)
for x in range(0, 100):
random_triangle(300,400,200,500,400,100)
Try running again the above code with the randintfunction. You will see that you will get an error message.
尝试使用该randint函数再次运行上述代码。您将看到您将收到一条错误消息。
回答by James Lawson
A rangein python is something that includes the lower-bound but does not include the upper-bound. At first, this may seem confusing but it is intentional and it is used throughout python.
python 中的范围是包含下限但不包含上限的东西。起初,这可能看起来令人困惑,但它是故意的,并且在整个 python 中都使用。
list(range(4, 10))
# [4, 5, 6, 7, 8, 9]
# does not include 10!
xs = ['a', 'b', 'c', 'd', 'e']
xs[1:4]
# [xs[1], xs[2], xs[3]]
# does not include xs[4]!
bisect.bisect_left('Hyman', names, 2, 5)
# perform a binary search on names[2], names[3], names[4]
# does not include names[5]!
random.randrange(4, 8)
# picks a random number from 4, 5, 6, 7
# does not include 8!
In mathematics, this is called a half-open interval. Python chooses to use half-intervals because they avoid off-by-one errors:
在数学中,这称为半开区间。Python 选择使用半间隔是因为它们避免了一对一错误:
[to avoid off-by-one errors] ... ranges in computing are often represented by half-open intervals; the range from m to n (inclusive) is represented by the range from m (inclusive) to n + 1 (exclusive)
[避免一对一错误] ...计算中的范围通常由半开区间表示;m到n(含)的范围用m(含)到n+1(不含)的范围表示
And so as a result, most python library functions will use this idea of half-open ranges when possible.
因此,大多数 python 库函数将在可能的情况下使用这种半开范围的想法。
However randintis one that does notuse half-open intervals.
然而randint是一种不使用半开区间的方法。
random.randint(4, 8)
# picks a random number from 4, 5, 6, 7, 8
# it does indeed include 8!
The reason is historical:
历史原因:
- randintwas added early in v1.5circa 1998 and this function name was used for generating both random floating-point numbers randomly and integersrandomly
- randrangewas added in python in v1.5.2. In v2.0, a notice was added saying that randint is deprecated.
- the deprecation notice for randint has since been removed
- randint在早期加入V1.5大约1998,并用于随机和生成两个随机浮点数此函数名的整数随机
- randrange在v1.5.2 中被添加到 python 中。在v2.0 中,添加了一条通知,指出 randint 已被弃用。
- 此后,randint 的弃用通知已被删除
randint started off as an earlier library function that didn't include half-open interval because this idea was less cemented in python at the time.
randint 一开始是一个较早的库函数,它不包含半开区间,因为这个想法当时在 python 中不太牢固。
回答by Anonymous
Actually... randint()uses randrange()to generate random integers.
实际上...randint()用于randrange()生成随机整数。
>>> randint(1.0,2.1)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
randint(1.0,2.1)
File "C:\Users\Anonymous\AppData\Local\Programs\Python\Python37\lib\random.py", line 222, in randint
return self.randrange(a, b+1) <----- LOOK HERE
File "C:\Users\Anonymous\AppData\Local\Programs\Python\Python37\lib\random.py", line 195, in randrange
raise ValueError("non-integer stop for randrange()")
ValueError: non-integer stop for randrange()

