random_sample() function in NumPy array
0 161
Introduction
Generating random numbers is a crucial aspect in various fields such as data science, simulations, and algorithm testing. NumPy offers several utilities to create random values, and one of these is the random_sample()
function. This function helps produce random floating-point numbers within the range [0.0, 1.0), making it very useful for different programming and analytical tasks.
Understanding the random_sample() Function
The numpy.random.random_sample()
method generates random floats sampled from a uniform distribution between 0.0 (inclusive) and 1.0 (exclusive). It can return a single float or an array of floats depending on the input argument specifying the desired shape.
Syntax
numpy.random.random_sample(size=None)
- size: Optional parameter that defines the output shape. If omitted, a single float value is returned.
Example 1: Generate a Single Random Float
import numpy as np value = np.random.random_sample() print("Random float:", value)
This outputs a single float number like:
Random float: 0.473829182
Example 2: Create a 1-D Array of Random Floats
import numpy as np array_1d = np.random.random_sample(5) print("1-D Array:", array_1d)
Sample output:
1-D Array: [0.12 0.89 0.37 0.66 0.43]
Example 3: Create a 2-D Random Float Array
import numpy as np array_2d = np.random.random_sample((3, 2)) print("2-D Array:\n", array_2d)
Possible output:
2-D Array: [[0.24 0.75] [0.93 0.05] [0.38 0.49]]
When to Use random_sample()
The random_sample()
function is ideal when you need uniformly distributed random floats between 0 and 1. This is commonly needed for:
- Initializing random values in simulations
- Creating synthetic datasets
- Random sampling in statistical modeling
- Testing algorithms with randomized inputs
Additional Notes
- The function always returns floats within the range [0.0, 1.0).
- You can specify the output shape using the
size
parameter. - For numbers in a different range, multiply or transform the output accordingly.
Conclusion
The random_sample()
function in NumPy is a straightforward and flexible method to generate random floating-point numbers between 0 and 1. Its versatility in returning single values or arrays makes it a handy tool for anyone working with random data in Python.
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!

Share:
Comments
Waiting for your comments