Generate random integers between 0 and 9

前端 未结 19 1834
无人共我
无人共我 2020-11-22 15:37

How can I generate random integers between 0 and 9 (inclusive) in Python?

For example, 0, 1, 2, 3, 4

19条回答
  •  臣服心动
    2020-11-22 16:10

    I would try one of the following:

    1.> numpy.random.randint

    import numpy as np
    X1 = np.random.randint(low=0, high=10, size=(15,))
    
    print (X1)
    >>> array([3, 0, 9, 0, 5, 7, 6, 9, 6, 7, 9, 6, 6, 9, 8])
    

    2.> numpy.random.uniform

    import numpy as np
    X2 = np.random.uniform(low=0, high=10, size=(15,)).astype(int)
    
    print (X2)
    >>> array([8, 3, 6, 9, 1, 0, 3, 6, 3, 3, 1, 2, 4, 0, 4])
    

    3.> random.randrange

    from random import randrange
    X3 = [randrange(10) for i in range(15)]
    
    print (X3)
    >>> [2, 1, 4, 1, 2, 8, 8, 6, 4, 1, 0, 5, 8, 3, 5]
    

    4.> random.randint

    from random import randint
    X4 = [randint(0, 9) for i in range(0, 15)]
    
    print (X4)
    >>> [6, 2, 6, 9, 5, 3, 2, 3, 3, 4, 4, 7, 4, 9, 6]
    

    Speed:

    np.random.randint is the fastest, followed by np.random.uniform and random.randrange. random.randint is the slowest.

    ► Both np.random.randint and np.random.uniform are much faster (~8 - 12 times faster) than random.randrange and random.randint .

    %timeit np.random.randint(low=0, high=10, size=(15,))
    >> 1.64 µs ± 7.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    
    %timeit np.random.uniform(low=0, high=10, size=(15,)).astype(int)
    >> 2.15 µs ± 38.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    
    %timeit [randrange(10) for i in range(15)]
    >> 12.9 µs ± 60.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    
    %timeit [randint(0, 9) for i in range(0, 15)]
    >> 20 µs ± 386 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    

    Notes:

    1.> np.random.randint generates random integers over the half-open interval [low, high).

    2.> np.random.uniform generates uniformly distributed numbers over the half-open interval [low, high).

    3.> random.randrange(stop) generates a random number from range(start, stop, step).

    4.> random.randint(a, b) returns a random integer N such that a <= N <= b.

    5.> astype(int) casts the numpy array to int data type.

    6.> I have chosen size = (15,). This will give you a numpy array of length = 15.

提交回复
热议问题