A Quick Guide to Random Numbers using Python Numpy With Examples

Numpy package offers the random module for the purpose of generating random numbers in Python. In this tutorial, we are going to learn how to use this module. We will learn what all functionalities this module has to offer.

Let’s get started!

What are Random Numbers?

 Random Numbers are ones that cannot be predicted logically. It just doesn’t need to be different every time. It also needs to be unpredictable.

Since computers generating a random number needs to works on an algorithm, these are called Pseudo-Random Numbers.

We will learn how to generate random numbers and arrays using Numpy.

How to Generate Random Numbers using Python Numpy?

To generate random numbers in Python, we will first import the Numpy package.

Now we can generate a number using :

Output :

On running it again you get :

It always returns a number between 0 and 1. Alternatively, you can also use:

Output:

On running it again we get :

We can use this to create Numpy arrays with random numbers that follow a normal distribution.

How to create a random array that follows a normal distribution?

A normal distribution is one in which the mean, mode, and median are equal. The data is symmetrically split around the center in this case. The graph of a normal distribution looks like a bell. This is why it is also called the ‘Bell Curve’.

To create an array with random numbers following a normal distribution use:

Output:

On running it again we get:

We can create an array of 5 as well.

Output:

This can be useful for assigning random weights before training a model.

We can also create Numpy arrays that follow a uniform distribution.

How to create a random array that follows a uniform distribution?

To create an array with random entries that follow a uniform distribution use :

Output :

On running it again we get :

How to choose randomly from a list?

Sometimes you need to randomly pick a number from a list. You can do this using the choice method under the random module:

Output:

On running it again, we get :

You can also use it for choosing characters or strings from a list.

Output :

On running it again we get :

How to randomly choose numbers from a set for filling an array?

You can also create arrays and matrices that have numbers randomly chosen from a list.

We will have to provide a list of options and using that the choice method will create a matrix of mentioned size.

Output :

On running it again we get :

Conclusion

This tutorial was about the random module under Numpy Package. We learned how to make arrays that follow normal and uniform distributions. We also learned how to use the choice method to choose randomly from a list.

By admin

Leave a Reply