Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

numpy
python
random number
communitycreator

What are random numbers in NumPy?

Onyejiaku Theophilus Chidalu

Overview

A random number is a number that cannot be predicted logically. A random number does not necessarily mean a different number each time.

Note: Any random number generated through any generation algorithm is called a pseudo-random number. This is because the algorithm can repeat the sequence, and the numbers are not entirely random.

Bearing that in mind, we can say that a program written to generate a random number is never truly random.

In this shot, we’ll take a look at how to generate pseudo-random numbers.

To generate a pseudo-random number in NumPy, we will need the random module offered by NumPy.

Example

In the code below, we will generate a pseudo-random integer between 0 and 10:

# importing the random module from numpy
from numpy import random

# using the randit() method to generate random integers from 0 to 10
x = random.randint(10)

# printing the random numbers
print(x)
Printing a pseudo-random number

Code explanation

  • Line 2: We import the random module from NumPy.
  • Line 5: We generate a random integer number between 0 and 10 using the randit() function.
  • Line 8: We print the pseudo-random number.

Note: The randint() function is used to generate pseudo-random integers.

Let’s take a look at another example.

Example

In the code below, we want to use the rand() function to generate a pseudo-random float number between 0 and 1.

# importing the random module from numpy
from numpy import random

# using the rand() method to generate random integers from 0 to 10
x = random.rand(1)

# printing the random float numbers
print(x)
Printing pseudo-random float numbers

Code explanation

  • Line 2: We import the random module from NumPy.
  • Line 5: We generate a random float number between 0 and 1 using the rand() function.
  • Line 8: We print the pseudo-random float number.

Note: The rand() function is used to generate pseudo-random float numbers.

RELATED TAGS

numpy
python
random number
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring