NumPy Random is from NumPy, whereas Python Random is a module in Python. That is, Python random is NOT part of NumPy.
This tutorial uses two examples to show the difference between NumPy Random and Python Random.
Example 1
Python Random’s randint only has parameters of the range, whereas NumPy random’s randint has the additional parameter of size.
Python:
random.randint(low, high): Return a random integer.
Numpy:
np.random.randint(low, high=None, size=None, dtype=int): Return (multiple) integers.
The following is the code example to demonstrate the difference. We can see that Python Random randint can only return 1 integer, whereas NumPy one can return more than 1 integer.
# importing Python Random
import random
# generate an integer via Python Random
Generated_number_1 = random.randint(2, 90)
print("Generated by Python Random: \n", Generated_number_1 )
# importing NumPy
import numpy as np
# generate an integer via NumPy Random
Generated_numbers = np.random.randint(2, 90, 3)
print("Generated by NumPy Random: \n", Generated_numbers )
The following is the output from Python Random and NumPy Random.
Generated by Python Random: 13 Generated by NumPy Random: [26 19 23]
Example 2
Python random.random will only return 1 floating number in [0,1), whereas NumPy’s random.rand() allows you to define the dimension of random numbers from [0,1).
Python:
random.random(): Return 1 random number in [0,1).
Numpy:
np.random.rand(d0, d1, …, dn): Return random numbers in [0,1) with different dimensions.
The following is the code example to demonstrate the difference between Python Random and NumPy Random.
# importing Python Random
import random
# generate a floating number in [0,1) via Python Random
Generated_number_1 = random.random()
print("Generated by Python Random: \n", Generated_number_1 )
# importing NumPy
import numpy as np
# generate floating numbers via NumPy Random
# d0=3, d1=4, size of 3x4 array in the range of [0, 1)
Array_numbers = np.random.rand(3,4)
print("Generated by NumPy Random: \n",Array_numbers)
The following is the output. Python’s random.random() only returns 1 number, whereas NumPy’s random.rand() returns an array of 12 numbers.
Generated by Python Random: 0.7689563885870707 Generated by NumPy Random: [[0.07768637 0.92770737 0.37410864 0.62537941] [0.83826093 0.08792431 0.09093518 0.95346045] [0.05844943 0.32099627 0.49624559 0.30395634]]