Sometimes,for testing purpose or for some other reasons we need to generate random numbers and data.In these post I am going to show you how can you **generate random numbers** **using python **native **random** **module **and python external libraries like **Numpy**.

**Generating random numbers with random module**

**1. Generating numbers between [0 and 1)**

We will start by generating just a single random number.We will use **random.random()** method to generate the number.

import random number=random.random() print(number)

If you run the above code,you will notice that it prints a floating point number between 0.0 and 1.0.Try to run it more time,and you will notice that,each time it prints different number. random.random() function returns a number that is **inclusive of 0.0 and exclusive of 1.0**

**2. Generating random floating point number between a range**

Sometimes,we need to generate floating point random numbers between a range of our choice. random module provides a function to achieve this too.You can use random modules uniform function to get floating point random number between a range.

import random number=random.uniform(1,10) print(number)

If you run the above code,you will get random numbers between 1 and 10.

**3. Generating integers using random module**

As you saw above,we have seen how to get floating point random numbers.But,what if we need whole numbers.Don’t worry about that. random module has many function to generate whole numbers.

We can generate random whole numbers between a range usimg random modules’s randint() function. randint() function takes 2 arguments,1 being the lowest range and 2 being the highest range. Output random numbers are inclusive both lower and higher limits.

import random number=random.randint(1,10) print(number)

Run the above code and you will get numbers including 1 and 10.

What if you need 10 different random numbers between interval 1 and 5.Well,you can use a for loop.

import random for i in range(10): number=random.randint(1,5) print(number)

All the methods which we used above,uses uniform distribution to generate random numbers.Uniform Distribution is a distribution where each element has equal chance of being selected.But,what if you want to model a situation,where **all elements have different chances of being selected**.This situation **will follow the normal distribution according to the “Central Limit Theorem”**

Normal distribution is a distribution, which we can describe using two things, mean and variance.It looks like a bell shape, hence it is also called bell curve.As you can see in image,bell peak is higher at x=0 and these is the mean of distribution**(μ)** and according to the value std. deviation**(σ)**, distribution is closer to the mean or away from the mean.

We can use random module to generate random numbers from normal distribution.

**4. Generating random numbers from Normal Distribution**

To generate random numbers from Normal Distribution,we need to use random modules’s **normalvariate()** function. **normalvariate() **function takes 2 arguments,mean and standard deviation.Let’s generate 20 random numbers from Normal Distribution.

import random for i in range(20): number=random.normalvariate(5,0.1) print(number) ######OUTPUT###### """ 5.0048690456791824 5.032909830859992 4.952667247176852 4.95000654775572 5.000942948610525 4.880191001603798 5.089130469655058 5.1025595580343115 4.968748515070382 5.130538582983823 4.943876181110818 5.090276580648151 5.019514136680288 5.0497182237376315 5.006413482446224 4.926534724770444 5.037730284048333 4.992547156963858 5.140585004309863 4.977089487630846 """

Look at the output closely and you will notice 12 from 20 values are 5.xx **(xx be the numbers after . ) **and rest values are close to 5 like 4.99 ,4.97. But,why so? As our std. deviation from mean is 0.1 which is very less hence number are close to mean.In these case,bell curve will be very narrow because all the values are near the mean which is 5.

Let’s increase the value of std. deviation from 0.1 to 6.

import random for i in range(20): number=random.normalvariate(5,0.1) print(number) #####OUTPUT#### """ 8.935276903733914 4.582326808048557 8.930502213170005 11.480577428246882 -3.4576792810198906 7.465109926506799 1.7603227989000354 11.059216614438238 -3.7317804953117637 10.907816500657674 1.6820854907748108 10.468492305480684 6.661196610638562 8.842234808147978 13.86649605060158 17.539835819911506 -10.232561378919586 -0.18846661727118708 6.292965295227786 2.036133701124152 """

Now you can see that,values are far away from mean because std. deviation is large.In these case,bell curve will be flatter and wider.

**5. Choosing random strings from a list**

Suppose you want to draw name of a lucky person from a list of names randomly.You can use random module to do these.But as names are of type string ,you cannot use random() as it only works for integers.You have to use **choice() **function to randomly select a name from a list.

import random names=["Tom","Jerry","Doraemon","Hattori"] name=random.choice(names) print(name)

Run the above code,and you will see the output.

**Generating random numbers using Numpy** **module**

Numpy is a external python library which is optimised for numeric operation. Numpy is very powerful if you want to generate random numbers for more than one dimensions like matrix.

**1. Generating random numbers with numpy.random.rand()**

**numpy.random.rand()** can be use to generate random numbers and fill in the specified shapes of array.It takes shape of resulting array as an arguments but if shape is not provided ,it returns a float.

import numpy number=numpy.random.rand() print(number) print(type(number)) ####OUTPUT#### """ 0.56048 <class 'float'> """ #### 1-d array#### array=numpy.random.rand(3) print(array) print(type(array)) ####OUTPUT#### """ [0.03393761 0.20119999 0.7545923 ] <class 'numpy.ndarray'> """ #### 2-d array### array=numpy.random.rand(3,2) print(array) print(type(array)) ####OUTPUT#### """ [[0.58037805 0.37065693] [0.5380439 0.00770253] [0.97320564 0.03604133]] <class 'numpy.ndarray'> """

You can see that,when I gave 0 arguments to rand(),it returns a single float number which is of type float,but when I pass arguments 3,it returns a 1-D arrays and when I pass arguments 3,2 to rand() function it returns a n-D array of shape (3,2) and you can check ,its type is <class ‘numpy.ndarray’>.

**2.Generating random numbers from ***Standard Normal Distribution* with numpy.random.randn()

*Standard Normal Distribution*with numpy.random.randn()

Standard Normal distribution is a distribution where **mean is 0 and std. deviation is 1**.We can use numpy.random.rand() function to generate numbers which follows std. Normal Distribution. If no arguments are given,it returns a single floating point number.If arguments are given,it returns n-D array of given shape filled with random numbers.

import numpy number=numpy.random.randn() print(number) print(type(number)) ####OUTPUT#### """ 0.14870368972262935 <class 'float'> """ ### 1-D array number=numpy.random.randn(2) print(number) print(type(number)) ####OUTPUT#### """ [-1.52232604 0.74424254] <class 'numpy.ndarray'> """ ### 2-D array number=numpy.random.randn(2,4) print(number) print(type(number)) ####OUTPUT#### """ [[-1.12248418 1.3617688 1.16609203 -0.28733747] [-1.043864 -0.6386792 -0.05689096 -0.33597422]] <class 'numpy.ndarray'> """

**3. Generate random numbers from Normal Distribution numpy.random.randn()**

If we want to use Normal Distribution instead of Std. Normal Distribution with variable mean and variance to generate random numbers with numpy.random.randn(),we need to do a trick.If we want to generate a sample from a Normal distribution of N(μ,σ^{2}),use below formula:

**sigma * np.random.randn(…) + mu**

where σ^{2} is variance or square of std. deviation and μ is the mean of distribution. If you have variance,then you can take square root of it to get sigma.

Suppose we want want to generate a (2,4) array from a Normal Distribution of mean 3 and variance 6.25 {N(3,6.25)}, we can achieve this by

import numpy array=2.5 * numpy.random.randn(2,4) +3 print(array) ####OUTPUT#### """ [[4.20316122 3.94947546 2.72173302 6.22396449] [3.74302471 2.72211189 4.21323564 0.99165549]] """

**4. Generating random integers using numpy.random.randint() **

Above all methods were returning floating point values,but **numpy.random.randint()** can be used to get random numbers which are integers.

**random.randint()** takes 4 arguments** (low,high,size,dtype)** from which 1’st argument is mandatory and others are optional.If low is specified,then it returns values randomly but it is exclusive of the low value.If high values is specified,then random numbers are inclusive of low value and exclusive of high value.

import numpy number=numpy.random.randint(1) print(number) ####OUTPUT#### # 0 ############################################################ number=numpy.random.randint(1,2) print(number) ####OUTPUT#### # 1 ############################################################ array=numpy.random.randint(2,size=5) print(array) ####OUTPUT#### # [0 0 0 0 1] ############################################################# array=numpy.random.randint(3,size=(2,2)) print(array) ####OUTPUT#### """ [[0 2] [1 0]] ""

**5. Generating random numbers using numpy.random.choice() **

This method is used to randomly generate numbers from a given list.It takes 4 arguments.

*numpy.random.choice(a, size=None, replace=True, p=None)*

First argument **(a)** is 1-D array or Single integer number,and we just need to provide range of array and python generates array for that range.**size** is shape of output.If not provided,then its None and single number is returned.**replace** is is either True or False.True means samples will be drawn with replacement and false means samples will be drawn without replacement. By default replace is True.

#### 1.**Generating uniform random sample **

import numpy array=numpy.random.choice(10,5) print(array) #####OUTPUT#### # [4 5 3 4 8]

You can see that,first argument is 10,but internally it is treated as np.arange(10) which generates array of 10 integers from 0 to 9 and from his array 5 numbers are chosen. As,replace is True,you can see 4 is drawn 2 times.

#### 2.**Generating uniform random sample **

In uniform sample each element has equal chance of being selected.Suppose,you want to generate a number more often ,means you want to give a number more probability so that it will have more chance of being selected.

import numpy array=numpy.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0] print(array) #####OUTPUT#### # array([0, 3, 3])

As,first arguments is numpy.arange(5) which returns 5 numbers from 0-4 ([0,1,2,3,4]), we have provided probabilities for each numbers argument p. You can see 0.6 is the probability associated with number 3,because indexing starts with 0. In output,you can see from 3 randomly generated numbers ,3 is generated 2 times because its probability is more than other numbers, that is 0.6. * NOTE:PROBALITIES SHOULD SUM UP TO 1.*

**3. Generating random strings from a list**

import numpy cartoons=["Hattori","Doraemon","Perman","Ben 10","Oswald"] randoms=numpy.random.choice(cartoons,5,p=[0.2,0.5,0.0,0.2,0.1]) print(randoms) ####OUTPUT#### # ['Doraemon' 'Doraemon' 'Hattori' 'Doraemon' 'Doraemon']

As Doraemon is my favourite cartoon ,I have assigned highest probability to it,so that it will have more chance of being selected every-time.

That’s all for this guide.I hope I have covered all important function’s and explained everything in detail.If you have any doubt or suggestion,please drop a comment below.

*Thank You.*