Skip to main content
Please wait...
The np.random.randint and np.random.rand Numpy Functions
08 Apr, 2025

The np.random.randint and np.random.rand Numpy Functions

The np.random module in NumPy provides functions for generating random numbers. Two commonly used functions are np.random.randint and np.random.rand. 

 

np.random.randint

  • Purpose: Generates random integers from a specified range. 

  • Usage: np.random.randint(low, high=None, size=None, dtype=int) 

  • Parameters: 

  • low: The lowest integer (inclusive). 

  • high: The highest integer (exclusive). If not provided, the range is [0, low). 

  • size: The shape of the output array. If not provided, a single integer is returned. 

  • dtype: The desired data type of the output array. 

  •  

  • Example: 

 import numpy as np 
 random_integers = np.random.randint(1, 10, size=(3, 2)) 
 print(random_integers) 
  

This might output: 

  [[3 7] 
   [1 9] 
   [4 6]] 
  

np.random.rand 

  • Purpose: Generates random numbers from a uniform distribution over the interval [0, 1). 

  • Usage: np.random.rand(d0, d1, ..., dn) 

  • Parameters: The dimensions of the returned array. 

 

Example: 1-D Array 

import numpy as np 
random_array_1d = np.random.rand(5) 
print(random_array_1d) 
  

This will out put a one dimensional array of random floating point numbers such as: 

[0.5488135  0.71518937 0.60276338 0.54488318 0.4236548] 
  

Example: Multi-Dimensional Array 

import numpy as np 
random_array_multi = np.random.rand(3, 2) 
print(random_array_multi) 
  

This might output: 

[[0.5488135  0.71518937] 
 [0.60276338 0.54488318] 
 [0.4236548  0.64589411]] 
  

Both functions are useful for different purposes: np.random.randint for generating random integers and np.random.rand for random floats. They are essential tools for simulations, random sampling, and various other applications in data science and machine learning.