What is the difference between random randint and randrange?

前端 未结 5 1920
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-07 16:25

The only difference that I know between randrange and randint is that randrange([start], stop[, step]) you can use the step and

相关标签:
5条回答
  • 2020-12-07 17:03

    A range in 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.

    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('jack', 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:

    [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)

    And so as a result, most python library functions will use this idea of half-open ranges when possible.

    However randint is one that does not use half-open intervals.

    random.randint(4, 8)
    #     picks a random number from 4, 5, 6, 7, 8
    #     it does indeed include 8!
    

    The reason is historical:

    • randint was added early in v1.5 circa 1998 and this function name was used for generating both random floating-point numbers randomly and integers randomly
    • randrange was 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 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.

    0 讨论(0)
  • 2020-12-07 17:05

    The difference between the two of them is that randint can only be used when you know both interval limits. If you only know the first limit of the interval randint will return an error. In this case you can use randrange with only one interval and it will work. Try run the following code for filling the screen with random triangles:

    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 randint function. You will see that you will get an error message.

    0 讨论(0)
  • 2020-12-07 17:09

    The docs on randrange say:

    random.randrange([start], stop[, step])

    Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object.

    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 n elements, I suppose. Most useful for getting a random index, I suppose.

    While randint is documented as:

    random.randint(a, b)

    Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1)

    So randint is for when you have the maximum and minimum value for the random number you want.

    0 讨论(0)
  • 2020-12-07 17:16

    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)
    
    0 讨论(0)
  • 2020-12-07 17:21

    Actually... randint() uses randrange() to generate random integers.

    >>> 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()
    
    0 讨论(0)
提交回复
热议问题