Random Numbers in Python
By: Anshuman Lall
Tags: Monte Carlo Simulation, Python, Data Science, Probability, Random Numbers

We make numerical calculations when the analytical solutions are not available. For example, if we flip a fair coin a large number of times, then we know “analytically” that the outcome will be heads or tails roughly equal the number of times (50% each). For complex systems, a numerical solution might be needed. This article covers a few ways to generate random numbers in Python for the purpose of numerical solutions to differential equations or Monte-Carlo simulations for forecasting.

Image by Clker-Free-Vector-Images from Pixabay

What are Random Numbers

Random numbers are the number chosen from a certain distribution. Depending on the distribution, some numbers are more likely to be chosen than others.

If the distribution is uniform, then all numbers have equally likely to be chosen.

If the distribution is Gaussian, then the numbers closer to the mean of the distribution have a higher probability of getting chosen. This is particularly useful when working with Brownian motion such as in particle diffusion.

Sometimes the distribution is not available, and a random entity needs to be drawn from a list with each entity (or number) having an equal probability of getting drawn. A modeler may choose to select the same entity again in subsequent draws (with replacement) and configure the code to not draw the same entity again (without replacement).

Random Library in Python

All you need information: random numbers on python.org, random numbers on analyticsvidhya. I am summarizing a few statements that are used more often.

import random # Random number between 0 and 1

random.random() # Get same random number every time

random.seed(1) # Random Number between a and b with uniform distribution

random.uniform(1,2) # Random Number with Normal distribution

random.gauss(1,2) # mu = 1 and sigma = 2

Quick Test 1: Red and Green balls

In some cases, random entities are needed to be picked from a list. For example, consider a typical interview question: What is the probability of drawing a green ball from a bag of 1 green and 4 red balls. Answer is 1/5 = 0.20. In other words, if I draw balls (with replacement) from the bag a large number of times (say, 100), then 20 of those would be green. Let’s test it programmatically.

green_ball_count = 0

for i in range(0,100):

new_ball = random.choice(['g', 'r', 'r', 'r', 'r'])

if new_ball == 'g':

green_ball_count = green_ball_count + 1 print (green_ball_count)

# output is 19 which is close to 20

Quick Test 2: Unfair Coin

Let’s assume that we only know the probabilities of the occurrence of the events. For example, in the case of an unfair coin, the head (H) occurs less than the tail (T). The probability(H) = 0.2 and probability(T) = 0.8.

H_count = 0

for i in range(0,10000):

new_flip = random.choices(['H', 'T'], weights=[0.2, 0.8])

if new_flip == ['H']: # notice that this function returns a list

H_count = H_count + 1 print (H_count)

# output is 1973 which is close to 2000

Law of Large Numbers

In both the above examples, we see that as the number of coin flips or balls drawn from the bag increase, the results from the numerical solution (simulation) come closer to the analytical solution. Let’s test this programmatically.

In the following code, a fair coin is flipped 1000 times. For the first few runs, the average numerical probability fluctuates but reaches a stable value of 0.5 for a larger number of flips.

for i in range(0,1000):

new_flip = random.choices(['H', 'T'], weights=[0.5, 0.5])

total_flips = total_flips + 1

if new_flip == ['H']: # notice that this function returns a list

H_count = H_count + 1 numerical_probability.append(H_count/total_flips) import matplotlib.pyplot as plt

plt.plot(numerical_probability)

plt.xlabel("flip counts")

plt.ylabel("numerical probability")

Numerical probability approaches the theoretical value of 0.5 for a large number of experiments

Real-World Applications

Safety Stock Calculations. Like an unfair coin, the demand for various items is not evenly distributed. In other words, there are more chances that the demand is below or above the forecast. Here is a research paper on this topic. Estimating Film Porosity and Thickness for Sensors: Brownian motion plays an important role in how aerosol particles get deposited on surfaces. Here is a research paper on this topic. Check out the “Predictions by the Numbers” documentary from Nova PBS.

Advanced Topics

Please free to reach out to me if you have any questions, suggestions, code requests, or if you found any errors in the above code.

Contact: https://www.linkedin.com/in/anshumanlall/