sample() function in NumPy array
0 168
Introduction
Generating random numbers is a fundamental aspect of many computational tasks, including simulations, data analysis, and machine learning. NumPy, a powerful library for numerical computing in Python, provides the random_sample()
function to generate random floating-point numbers. In this blog, we'll explore how to use this function effectively.
What is random_sample()?
The numpy.random.random_sample()
function returns random floats in the half-open interval [0.0, 1.0). It can generate a single random float or an array of random floats, depending on the shape specified.
Syntax
numpy.random.random_sample(size=None)
- size: Optional. The shape of the output array. If not specified, a single float is returned.
Examples
1. Generating a Single Random Float
import numpy as np value = np.random.random_sample() print("Random float:", value)
Output:
Random float: 0.123456789
2. Generating a 1-D Array of Random Floats
import numpy as np array_1d = np.random.random_sample(5) print("1-D Array:", array_1d)
Output:
1-D Array: [0.234 0.567 0.890 0.123 0.456]
3. Generating a 2-D Array of Random Floats
import numpy as np array_2d = np.random.random_sample((2, 3)) print("2-D Array:\n", array_2d)
Output:
2-D Array: [[0.789 0.012 0.345] [0.678 0.901 0.234]]
Use Cases
The random_sample()
function is useful in various scenarios:
- Simulations: Generating random numbers for Monte Carlo simulations.
- Data Analysis: Creating random datasets for testing algorithms.
- Machine Learning: Initializing weights in neural networks.
- Statistical Modeling: Sampling from a uniform distribution.
Conclusion
The random_sample()
function in NumPy is a simple yet powerful tool for generating random floating-point numbers. By understanding its syntax and applications, you can effectively incorporate it into your computational tasks.
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