random() function in NumPy array
0 160
Introduction
Working with random data is a common requirement in many programming tasks, including simulations, machine learning, and testing. NumPy, one of Python's most widely used scientific computing libraries, offers powerful tools for generating random numbers. Among them, the random()
function is frequently used to produce random float values between 0.0 and 1.0. In this blog, we’ll take a closer look at how the random()
function works and how you can use it effectively.
What Does random() Do?
The numpy.random.random()
function generates random float numbers from a uniform distribution in the half-open interval [0.0, 1.0). It can return a single value or a multi-dimensional array depending on the input parameters.
Syntax
numpy.random.random(size=None)
- size: (optional) Defines the shape of the array to generate. If no value is provided, a single float is returned.
Example 1: Generating a Single Random Float
import numpy as np value = np.random.random() print("Random float:", value)
Sample output:
Random float: 0.6532918405
Example 2: Creating a 1-D Array of Random Floats
import numpy as np array_1d = np.random.random(5) print("1-D Array:", array_1d)
Output:
1-D Array: [0.12 0.89 0.37 0.66 0.43]
Example 3: Creating a 2-D Random Float Array
import numpy as np array_2d = np.random.random((2, 3)) print("2-D Array:\n", array_2d)
Example output:
2-D Array: [[0.21 0.75 0.34] [0.96 0.13 0.59]]
Use Cases of random()
Here are some practical situations where random()
can be helpful:
- Creating synthetic datasets for testing models
- Initializing weights in neural networks
- Simulating random events or processes
- Shuffling or selecting elements randomly from arrays (when combined with indexing)
Difference Between random() and rand()
Both random()
and rand()
can produce random float values, but they belong to different parts of the NumPy API:
numpy.random.random()
: Called with a tuple for multi-dimensional shapes.numpy.random.rand()
: Takes multiple positional arguments instead of a shape tuple.
In practice, both produce the same type of output, but the way you define the output shape differs.
Conclusion
The random()
function in NumPy array is a simple yet powerful tool for generating random float values in the range [0.0, 1.0). It’s perfect for simulations, initializing data, and quick experimentation in Python projects. Understanding how and when to use it can make your numerical tasks more flexible and efficient.
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