How to Generate Random Numbers in Python
There are different ways, we can generate random numbers in Python. We can categorize them in following ways.
Random numbers generate from a list using Python random
Random numbers using Numpy Random
Lets go through the above methods one by one.
We need random package from Python. Lets import that.
import random
Using Python random package we can generate random integer number, generate random number from sequence, generate random number from sample etc. Do random? to learn more about all these methods.
How To Generate Python Random Integer Number in Range Using random.randint()
Lets start with an example.
print(random.randint(-10,-1))
print(random.randint(0,100))
print(random.randint(900,1000))
How To Generate Python Random Number in Range Using random.randrange()
The difference between random.randint() and random.randrange() method is that in random.randrange() we can give it a step size as shown below.
random.randrange(10,20,2)
In randrange, first two numbers define the range and the last one is the step size. Lets try one more time.
random.randrange(10,20,2)
Lets see if we can generate float number using random.randrange.
random.randrange(10.1,20.5,2)
I got following error...
ValueError: non-integer arg 1 for randrange()
random.randrange is only used for random integer number generation.
How To Generate Python Random Number From A Given User List Using random.choice()
We can also give random package a list of numbers and ask it to generate a random number.
Lets create a Python list of numbers
x = [1,50,67,900,10045]
random.choice(x)
Lets try again.
random.choice(x)
Lets try a list with floating numbers.
y = [1.1,50.1,67.5,900.5,10045.6]
random.choice(y)
Unlike random.randrange(), random.choice() works for floating numbers too.
How To Use random.shuffle() To Shuffle The List of Numbers
Well we can shuffle the list from using choice method. shuffle() will shuffle the list. Lets try it.
random.shuffle(y)
print(y)
As we got the list shuffled with random.shuffle() method
How To Generate Python Floating Random Number Between 0 and 1 using random.random()
random.random() is based on famous pseduo random number generator Mersenne Twister.
random.random()
Lets try again.
random.random()
Every time we run random.random(), We get a new random floating point number between 0 and 1. By default these numbers are generated from the uniform distribution which means probability of drawing or generating any random number between 0 and 1 is equal.
To make sure that we generate the same number, every time we run random.random(), we can give it a seed. Lets first show you an example.
random.seed(4)
print(random.random())
random.seed(4)
print(random.random())
As see we above, we got the same random floating number, when we gave it the same seed. Rember the number that we passed to seed is artibrary number here, as long as it is same, you would get same random floating number.
How To Sample From Python List using random.sample()
Sampling is often used in machine learning techniques. Python random.sample() can be used to sub sample data.
Lets create a list of 20 numbers first.
list_of_numbers = [i for i in range(20)]
list_of_numbers
Now using random.sample() we can get random sub sample of numbers from our list. lets try that.
random.sample(list_of_numbers,6)
second argument in random.sample() specifies how many random numbers we want from our original list.
How To Generate Random Numbers In Python From Various Distributions
Lets generate a random number from the uniform distribution.
random.uniform(0,1)
Lets generate a random number from the triangular distribution.
random.triangular(0,5,4)
In above command, the random number is generated between 0 and 5 and third argument is the mode. Please checkout wikipedia to learn more about the triangular distributions.
Lets generate a random number from most common distribution which is Gaussian distribution using random.gauss()
random.gauss(5,1)
In random.gauss() first argument is the mean and 2nd argument sigma is standard deviation. Lets try one more time.
random.gauss(5,1)
How To Generate Random Numbers In Python Using Numpy
Numpy has different pseudorandom generator implementation then Python. Numpy is very extensively used in machine learning and for doing complex matrix and mathematical calculations.
Using Numpy we can generate a sequence of random numbers with just one command.
Lets try numpy random.rand() function to generate 10 random numbers.
import numpy as np
from numpy.random import rand
rand(10)
As we see above using numpy we generated random array of numbers.
Numpy also has seed function, which will make sure that we get same sequence of numbers when we run numpy rand using seed function.
from numpy.random import seed
seed(4)
rand(10)
Lets try generating the numpy random numbers using same seed 4.
seed(4)
rand(10)
As we see above, we got the same sequence of numbers.
Similarly we can generate integers using numpy randint. Lets import randint.
from numpy.random import randint
randint(0,100)
To generate more than one number, pass number argument to numpy randint() and we would get an array of numbers.
randint(0,100,2)
How To Generate Numpy Array Of Random Numbers From Gaussian Distribution Using randn()
Lets first import numpy randn
from numpy.random import randn
seed(5)
randn(10)
As we see above, numpy randn(10) generated 10 numbers for a mean of 0 and variance of 1.
We can also generate a matrix of numbers from Gaussian Distribution. Lets say we want to generate a 2x2 matrix of Gaussian numbers using numpy randn.
seed(5)
randn(2,2)
Wrap Up!
I have shown above the usage of Python random package and Numpy random package to generate random numbers through examples. I hope you would find the post useful.
Related Notebooks
- How to Generate Embeddings from a Server and Index Them Using FAISS with API
- How to Plot a Histogram in Python
- How To Solve Linear Equations Using Sympy In Python
- How To Code RNN and LSTM Neural Networks in Python
- How To Take String Input From Command Line In Python
- How To Take Integer Input From Command Line In Python
- How To Solve Error Numpy Has No Attribute Float In Python
- How To Convert Python List To Pandas DataFrame
- How To Write DataFrame To CSV In R