The world is ruled by chance. Randomness stalks us every day of our life.
– Paul Auster
Random numbers surround us in the world of data science. Every now and then I need to quickly come up with some random numbers to run a thought experiment or to demonstrate a concept to an audience., but without having to download large data sets.
From the creation of dummy data to the random reproduction of the data for training and testing purposes or the initialization of weights of a neural network, we generate random numbers all the time in python. You will love this concept once you get the hang of it after this article.
In my opinion, Random number generation is a topic anyone in data science should know. I will walk you through the whole process of generating random numbers in Python here and also demonstrate it using different techniques.
New to Python? These two free courses will get you started:
Table of Contents
- Random library
- Sowing random numbers
- Generating random numbers in a range
- Randomly taking from a list
- Mix a list
- Generation of random numbers according to distributions
Generating Random Numbers in Python Using the Random Library
This is the good news: there are several ways to generate random numbers in python. The easiest method is to use random module. It is a module built into Python and does not require installation. This module uses a pseudo-random number generator (PRNG) known as Mersenne Twister to generate random numbers.
A pseudo-random number generator is a deterministic random number generator. Does not generate truly random numbers. Take a number as input and generate a random number for it.
Note: Do not use the random module to generate random numbers for security reasons. For cryptographic and security uses, you can use the mysteries module you use true random number generators (WHITE).
Sowing random numbers
As we discussed in the previous section, the random module takes a number as input and generates a random number for it. This initial value is known as a seed and the procedure is known as a seed..
The numbers we generate using pseudo-random number generators are deterministic. This means that they can be replicated using the same seed..
Let's understand with an example:
import random print('Random Number 1=>',random.random()) print('Random Number 2=>',random.random())
Here, i am using random function () which generates a random number in the range [0.0, 1.0]. Note here that I have not mentioned the value of the seed. By default, current system time in milliseconds is used as seed. Let's take a look at the output.
Both numbers are different due to the change in time during execution from the first statement to the second statement. Let's see what happens if we plant the generators with the same value:
random.seed(42) print('Random Number 1=>',random.random()) random.seed(42) print('Random Number 2=>',random.random())
We get the same numbers here. This is why pseudo-random number generators are deterministic and not used for security purposes because anyone who has the seed can generate the same random number.
Generating random numbers in a range
Up to now, we know how to create random numbers in the range [0.0, 1.0]. But, What if we have to create a number in a range other than this?
One way is to multiply and add numbers to the number returned by the random() function. For instance, random.random () * 3 + 2 will return numbers in range [2.0, 5.0]. But nevertheless, this is more of a workaround, not a direct solution.
Do not worry! The random module has your back here. Provides uniform() Y dating () functions that we can use for this purpose. Let's understand one by one.
uniform()
The uniform function () from the random modulus takes the start and end values of a range as arguments and returns a random floating point number in the range. [starting, ending]:
print('Random Number in range(2,8)=>', random.uniform(2,8))
dating ()
This function is similar to the uniform function (). The only difference is that the uniform function () returns floating point random numbers and the randint function () returns an integer. Also returns the number in the range [starting, ending]:
print('Random Number in a range(2,8)=>', random.randint(2,8))
Randomly taking from a list
choice() Y options () are the two functions provided by the random module that we can use to randomly select values from a list. Both functions take a list as an argument and randomly select a value from it. Can you guess what the difference is between choice() Y options () it is?
choice() just pick a single value from a list, while options () pick multiple values from a list with replacement. One great thing about these functions is that they also work on a list that contains strings. Let's see them in action:
a=[5, 9, 20, 10, 2, 8] print('Randomly picked number=>',random.choice(a)) print('Randomly picked number=>',random.choices(a,k=3))
As you can see, choice() returned a unique value of a Y options () returned three values of a. Here, k is the length of the list returned by options ().
One more thing you may notice in the responses returned by options () is that each value occurs only once. You can increase the probability that each value is chosen by passing an array like pesos al options () function. Then, let's increase the probability of 10 up to three more times and let's see the results:
for _ in range(5):
print('Randomly picked number=>',random.choices(a,weights=[1,1,1,3,1,1],k=3))
Here, we can see what happened 10 in each draw on the list. There is also a sample() function in random module that works similar to options () function but takes random samples from a list no replacement.
Mix a list
Let's say we don't want to select values from a list, but we just want to reorder them. We can do this using the shuffle() random module function. This shuffle() The function takes the list as an argument and shuffles the list instead:
print('Original list=>',a) random.shuffle(a) print('Shuffled list=>',a)
Note: the shuffle function () does not return a list.
Generation of random numbers according to distributions
A more surprising feature of the random module is that it allows us to generate random numbers based on different probability distributions. There are various functions like gauss(), expovariate (), etc., that help us to do this.
If you are not familiar with probability distributions, I recommend that you read this article: 6 Common Probability Distributions Every Data Science Professional Should Know.
gauss()
Let's start with the most common probability distribution, namely, normal distribution. gauss() is a function of the random modulus used to generate random numbers according to a normal distribution. Take the mean and standard deviation as an argument and return a random number:
for _ in range(5): print(random.gauss(0,1))
Here, trace 1000 random numbers generated by the gauss() function for mean equal to 0 and standard deviation as 1. You can see above that all the points are distributed around the mean and not widely distributed since the standard deviation is 1.
expovariate ()
The exponential distribution is another very common probability distribution that you will find. the expovariate () The function is used to obtain a random number according to the exponential distribution. It takes the value of lambda as an argument and returns a value of 0 to positive infinity if lambda is positive, and from negative infinity to 0 if lambda is negative:
print('Random number from exponential distribution=>',random.expovariate(10))
Final notes
I often use random numbers to create dummy data sets and for random sampling. I would love to know how you use random numbers in your projects, so do comment below with your thoughts and share them with the community.
If you found this article informative, Share it with your friends and comment below on your questions and comments. I have listed some amazing Python and data science related articles below for your reference:








