numpy
  1. numpy-random

random() - Common NumPy Functions

The random() function is a commonly used function in NumPy, which is a Python library used for scientific computing. The random() function is used to generate random numbers based on a defined probability distribution.

Syntax

The syntax for the random() function is as follows:

numpy.random.random(size=None)

Here, size is an optional parameter that specifies the shape of the output array. If it is not specified, a single random number is returned.

Example

Here is an example of how to use the random() function:

import numpy as np

# Generate a random number between 0 and 1
x = np.random.random()
print(x)

# Generate a 1D array of 5 random numbers
y = np.random.random(5)
print(y)

# Generate a 2D array of random numbers with a shape of 2x3
z = np.random.random((2,3))
print(z)

The output of this code will be:

0.5678661958176123
[0.31613471 0.12390757 0.65293993 0.42849949 0.69316864]
[[0.11953208 0.26692615 0.96596446]
 [0.73325796 0.77841528 0.97487399]]

In this example, we have used the random() function to generate a single random number, a 1D array of 5 random numbers, and a 2D array of random numbers with a shape of 2x3.

Output

The output of the random() function is a random number(s) between 0 and 1, based on the shape specified in the size parameter.

Explanation

The random() function is a useful function in NumPy that is used for generating random numbers. By default, it generates random numbers that are uniformly distributed between 0 and 1. The function is used to create test datasets for statistical analysis or machine learning models.

Use

The random() function is frequently used in machine learning to create test datasets and for feature scaling. It can also be used in simulations, game development, and cryptography.

Important Points

  • The random() function generates random numbers with a uniform distribution between 0 and 1.
  • The size parameter is optional, but when provided, it specifies the shape of the output array.
  • The function is useful in creating test datasets for statistical analysis or machine learning models.

Summary

The random() function is a commonly used function in NumPy used to generate random numbers. It generates random numbers that are uniformly distributed between 0 and 1. It is useful in creating test datasets, feature scaling, simulations, game development, and cryptography.

Published on: