Random Number Using Numpy
The random function provided by the Numpy module can be more useful for you as it provides little better functionality and performance as compared to the random module.
Method 1: Generating a list of random integers using numpy.random.randint function
This function returns random integers from the “discrete uniform” distribution of the integer data type.
Python3
# importing numpy module import numpy as np # print the list of 10 integers from 3 to 7 print ( list (np.random.randint(low = 3 ,high = 8 ,size = 10 ))) # print the list of 5 integers from 0 to 2 # if high parameter is not passed during # function call then results are from [0, low) print ( list (np.random.randint(low = 3 ,size = 5 ))) |
Output: [5, 3, 6, 7, 4, 5, 7, 7, 7, 7] [0, 2, 1, 2, 1]
Method 2. Generating a list of random floating values using numpy.random.random_sample function
This function return random float values in half open interval [0.0, 1.0).
Python3
import numpy as np # generates list of 4 float values print (np.random.random_sample(size = 4 )) # generates 2d list of 4*4 print (np.random.random_sample(size = ( 4 , 4 ))) |
output: [0.08035145 0.94966245 0.92860366 0.22102797] [[0.02937499 0.50073572 0.58278742 0.02577903] [0.37892104 0.60267882 0.33774815 0.28425059] [0.57086088 0.07445422 0.86236614 0.33505317] [0.83514508 0.82818536 0.1917555 0.76293027]]
The benefit of using numpy.random over the random module of Python is that it provides a few extra probability distributions which can help in scientific research.
Generating random number list in Python
Sometimes, in making programs for gaming or gambling, we come across the task of creating a list all with random numbers in Python. This task is to perform in general using loop and appending the random numbers one by one. But there is always a requirement to perform this in the most concise manner. Let’s discuss certain ways in which this can be done.