
- NumPy - Home
- NumPy - Introduction
- NumPy - Environment
- NumPy Arrays
- NumPy - Ndarray Object
- NumPy - Data Types
- NumPy Creating and Manipulating Arrays
- NumPy - Array Creation Routines
- NumPy - Array Manipulation
- NumPy - Array from Existing Data
- NumPy - Array From Numerical Ranges
- NumPy - Iterating Over Array
- NumPy - Reshaping Arrays
- NumPy - Concatenating Arrays
- NumPy - Stacking Arrays
- NumPy - Splitting Arrays
- NumPy - Flattening Arrays
- NumPy - Transposing Arrays
- NumPy Indexing & Slicing
- NumPy - Indexing & Slicing
- NumPy - Indexing
- NumPy - Slicing
- NumPy - Advanced Indexing
- NumPy - Fancy Indexing
- NumPy - Field Access
- NumPy - Slicing with Boolean Arrays
- NumPy Array Attributes & Operations
- NumPy - Array Attributes
- NumPy - Array Shape
- NumPy - Array Size
- NumPy - Array Strides
- NumPy - Array Itemsize
- NumPy - Broadcasting
- NumPy - Arithmetic Operations
- NumPy - Array Addition
- NumPy - Array Subtraction
- NumPy - Array Multiplication
- NumPy - Array Division
- NumPy Advanced Array Operations
- NumPy - Swapping Axes of Arrays
- NumPy - Byte Swapping
- NumPy - Copies & Views
- NumPy - Element-wise Array Comparisons
- NumPy - Filtering Arrays
- NumPy - Joining Arrays
- NumPy - Sort, Search & Counting Functions
- NumPy - Searching Arrays
- NumPy - Union of Arrays
- NumPy - Finding Unique Rows
- NumPy - Creating Datetime Arrays
- NumPy - Binary Operators
- NumPy - String Functions
- NumPy - Matrix Library
- NumPy - Linear Algebra
- NumPy - Matplotlib
- NumPy - Histogram Using Matplotlib
- NumPy Sorting and Advanced Manipulation
- NumPy - Sorting Arrays
- NumPy - Sorting along an axis
- NumPy - Sorting with Fancy Indexing
- NumPy - Structured Arrays
- NumPy - Creating Structured Arrays
- NumPy - Manipulating Structured Arrays
- NumPy - Record Arrays
- Numpy - Loading Arrays
- Numpy - Saving Arrays
- NumPy - Append Values to an Array
- NumPy - Swap Columns of Array
- NumPy - Insert Axes to an Array
- NumPy Handling Missing Data
- NumPy - Handling Missing Data
- NumPy - Identifying Missing Values
- NumPy - Removing Missing Data
- NumPy - Imputing Missing Data
- NumPy Performance Optimization
- NumPy - Performance Optimization with Arrays
- NumPy - Vectorization with Arrays
- NumPy - Memory Layout of Arrays
- Numpy Linear Algebra
- NumPy - Linear Algebra
- NumPy - Matrix Library
- NumPy - Matrix Addition
- NumPy - Matrix Subtraction
- NumPy - Matrix Multiplication
- NumPy - Element-wise Matrix Operations
- NumPy - Dot Product
- NumPy - Matrix Inversion
- NumPy - Determinant Calculation
- NumPy - Eigenvalues
- NumPy - Eigenvectors
- NumPy - Singular Value Decomposition
- NumPy - Solving Linear Equations
- NumPy - Matrix Norms
- NumPy Element-wise Matrix Operations
- NumPy - Sum
- NumPy - Mean
- NumPy - Median
- NumPy - Min
- NumPy - Max
- NumPy Set Operations
- NumPy - Unique Elements
- NumPy - Intersection
- NumPy - Union
- NumPy - Difference
- NumPy Random Number Generation
- NumPy - Random Generator
- NumPy - Permutations & Shuffling
- NumPy - Uniform distribution
- NumPy - Normal distribution
- NumPy - Binomial distribution
- NumPy - Poisson distribution
- NumPy - Exponential distribution
- NumPy - Rayleigh Distribution
- NumPy - Logistic Distribution
- NumPy - Pareto Distribution
- NumPy - Visualize Distributions With Sea born
- NumPy - Matplotlib
- NumPy - Multinomial Distribution
- NumPy - Chi Square Distribution
- NumPy - Zipf Distribution
- NumPy File Input & Output
- NumPy - I/O with NumPy
- NumPy - Reading Data from Files
- NumPy - Writing Data to Files
- NumPy - File Formats Supported
- NumPy Mathematical Functions
- NumPy - Mathematical Functions
- NumPy - Trigonometric functions
- NumPy - Exponential Functions
- NumPy - Logarithmic Functions
- NumPy - Hyperbolic functions
- NumPy - Rounding functions
- NumPy Fourier Transforms
- NumPy - Discrete Fourier Transform (DFT)
- NumPy - Fast Fourier Transform (FFT)
- NumPy - Inverse Fourier Transform
- NumPy - Fourier Series and Transforms
- NumPy - Signal Processing Applications
- NumPy - Convolution
- NumPy Polynomials
- NumPy - Polynomial Representation
- NumPy - Polynomial Operations
- NumPy - Finding Roots of Polynomials
- NumPy - Evaluating Polynomials
- NumPy Statistics
- NumPy - Statistical Functions
- NumPy - Descriptive Statistics
- NumPy Datetime
- NumPy - Basics of Date and Time
- NumPy - Representing Date & Time
- NumPy - Date & Time Arithmetic
- NumPy - Indexing with Datetime
- NumPy - Time Zone Handling
- NumPy - Time Series Analysis
- NumPy - Working with Time Deltas
- NumPy - Handling Leap Seconds
- NumPy - Vectorized Operations with Datetimes
- NumPy ufunc
- NumPy - ufunc Introduction
- NumPy - Creating Universal Functions (ufunc)
- NumPy - Arithmetic Universal Function (ufunc)
- NumPy - Rounding Decimal ufunc
- NumPy - Logarithmic Universal Function (ufunc)
- NumPy - Summation Universal Function (ufunc)
- NumPy - Product Universal Function (ufunc)
- NumPy - Difference Universal Function (ufunc)
- NumPy - Finding LCM with ufunc
- NumPy - ufunc Finding GCD
- NumPy - ufunc Trigonometric
- NumPy - Hyperbolic ufunc
- NumPy - Set Operations ufunc
- NumPy Useful Resources
- NumPy - Quick Guide
- NumPy - Cheatsheet
- NumPy - Useful Resources
- NumPy - Discussion
- NumPy Compiler
NumPy - Random Generator
NumPy Random Generator
The random generator in NumPy is used to generate random numbers and perform random sampling.
The random module in NumPy offers a wide range of random number generation functions, from generating random integers and floating-point numbers to more complex distributions like normal, uniform, and binomial distributions.
In this tutorial, we will explore how to use the NumPy Random Generator to generate random data and discuss the important functions available in this module.
The NumPy Random Module?
The NumPy random module is a submodule within the NumPy library that contains functions for generating random numbers, performing random sampling, and generating random distributions. It provides the numpy.random package, which supports the creation of random numbers from various probability distributions like uniform, normal, and binomial.
By using NumPy's random generator, we can generate random values that can be used for simulations, randomized testing, or even cryptographic operations. The random numbers generated are pseudo-random, meaning they are generated using a deterministic process but appear random.
The sequence of random numbers can be controlled using a random seed, which ensures reproducibility in simulations and experiments.
How Does NumPy's Random Generator Work?
The NumPy random number generator is built on top of a pseudorandom number generator (PRNG) algorithm called the Mersenne Twister. The key feature of a PRNG is that it generates a sequence of numbers that approximates true randomness, but it is determined by an initial value, called a seed.
By setting the same seed, you can ensure that the sequence of random numbers is the same every time you run your code, which is important for reproducibility in scientific experiments.
Seeding the Random Generator
To control the random number generation process, NumPy provides the numpy.random.seed() function, which sets the seed for the random number generator. This allows you to generate the same random numbers every time you run your program.
Example
In the example below, by setting the same seed value (42 in this case), we get the same sequence of random numbers every time we run the code. This helps in ensuring consistency during experiments and debugging −
import numpy as np # Set the seed for reproducibility np.random.seed(42) # Generate random numbers random_numbers_1 = np.random.random(5) # Generate the same random numbers with the same seed np.random.seed(42) random_numbers_2 = np.random.random(5) # Display the results print("First random numbers:", random_numbers_1) print("Second random numbers:", random_numbers_2)
Following is the output obtained −
First random numbers: [0.37454012 0.95071431 0.73199394 0.59865848 0.15601864] Second random numbers: [0.37454012 0.95071431 0.73199394 0.59865848 0.15601864]
Generating Random Numbers
NumPy offers various functions for generating random numbers. Here, we will explore some of the most commonly used functions −
Random Float Numbers
The numpy.random.random() function generates random floating-point numbers between 0 and 1. You can specify the shape of the output array by passing the desired dimensions as an argument. For example −
import numpy as np # Generate 5 random float numbers between 0 and 1 random_floats = np.random.random(5) print("Random float numbers:", random_floats)
The result produced is as follows −
Random float numbers: [0.96177309 0.75071326 0.44828032 0.53441928 0.56717514]
Random Integers
The numpy.random.randint() function generates random integers within a specified range. You can specify the low and high values, and it will return integers between the low (inclusive) and high (exclusive) values. Here is an example −
import numpy as np # Generate 5 random integers between 10 (inclusive) and 100 (exclusive) random_integers = np.random.randint(10, 100, size=5) print("Random integers:", random_integers)
After executing the above code, we get the following output −
Random integers: [13 38 56 94 78]
Random Numbers from Normal Distribution
The numpy.random.normal() function generates random numbers from a normal (Gaussian) distribution with a specified mean and standard deviation. You can also specify the size of the output array. Here's how it works −
import numpy as np # Generate 5 random numbers from a normal distribution with mean=0 and std=1 random_normal = np.random.normal(0, 1, 5) print("Random numbers from normal distribution:", random_normal)
The output obtained is as shown below −
Random numbers from normal distribution: [ 0.52379705 0.3169246 0.76473415 -0.73006407 -0.50259886]
Random Numbers from Uniform Distribution
The numpy.random.uniform() function generates random numbers from a uniform distribution within a given range. Here's an example of generating 5 random numbers between 1.0 and 10.0−
import numpy as np # Generate 5 random numbers between 1.0 and 10.0 random_uniform = np.random.uniform(1.0, 10.0, 5) print("Random numbers from uniform distribution:", random_uniform)
The result produced is as follows −
Random numbers from uniform distribution: [4.92412702 2.57524084 1.71870242 3.71017627 6.19920522]
Random Sampling with Replacement
Sometimes, we need to randomly select elements from an array. NumPy provides the numpy.random.choice() function, which allows you to perform random sampling with or without replacement.
Example
In the example below, the function selects 3 random elements from the array with replacement, meaning elements can be selected multiple times −
import numpy as np # Define an array of elements array = np.array([1, 2, 3, 4, 5]) # Randomly select 3 elements from the array with replacement sample_with_replacement = np.random.choice(array, 3, replace=True) print("Random sample with replacement:", sample_with_replacement)
The result produced is as follows −
Random sample with replacement: [5 3 5]
Shuffling an Array
Another useful operation is shuffling the elements of an array randomly. NumPy provides the numpy.random.shuffle() function for this purpose. It randomly permutes the elements of an array in-place.
Example
In the following example, we are shuffling an array in NumPy using the numpy.random.shuffle() function −
import numpy as np # Define an array array = np.array([1, 2, 3, 4, 5]) # Shuffle the array in place np.random.shuffle(array) print("Shuffled array:", array)
The output obtained is as shown below −
Shuffled array: [4 2 3 5 1]