Cornellius Yudha Wijaya
2024-12-06 10:00:00
www.kdnuggets.com
Image by studio4rt on Freepik
The simulation process is essential in mathematical and statistical analysis as it can represent the behavior condition for the intended scenario. In other words, simulation can analyze things with parameters and situations with wants.
NumPy is a powerful Python package that can be used for many numerical and statistical processes, including random simulation and Monte Carlo methodology. Random simulation is a computational technique that involves random generation to create multiple scenarios. Monte Carlo is a unique technique that uses random sampling in higher numbers to approximate the actual values or results.
With NumPy, we can perform the random simulation process and use the Monte Carlo methodology. How to do that? Let’s get into it.
Random Process Simulation with NumPy
Let’s start generating random data with NumPy. For this tutorial, we need the NumPy package ready. Please install it if you haven’t.
Once it is ready, we can start simulating the random process. Before that, let’s set a seed number for the reproducibility process.
import numpy as np
np.random.seed(100)
With the seed ready, let’s try a simple random number generation process. You can generate a random number with the following code.
Output>>
array([0.54340494, 0.27836939, 0.42451759, 0.84477613, 0.00471886])
Generating random numbers from certain distributions is also possible. For example, this code would draw a number from the normal distribution.
np.random.normal(0, 1, 10)
Output>>
array([ 0.35467445, -0.78606433, -0.2318722 , 0.20797568, 0.93580797,
0.17957831, -0.5771615 , -0.53337271, -0.22540212, -0.31491934])
We understand that NumPy can generate random numbers, so we will try to perform a random simulation process. The first thing we would try is the random walk simulation.
Random walk simulation is a simple mathematical modeling in which we describe a succession of random steps that constitute a path. Each step is independent of the previous step, so the direction can be found anywhere. It’s useful as it could simulate how animals walk in the forest or how stock prices fluctuate.
Let’s set up the code simulation for a random walk.
def random_walk_1d(steps):
walk = np.random.choice([-1, 1], size=steps)
position = np.cumsum(walk)
return position
In the code above, we simulate a one-dimensional random walk with the choice method in NumPy. We select between values 1 and -1, and the selection happens in “steps” time. Then, we cumulatively sum the steps to see where the walk is at any given step.
steps = 1000
position = random_walk_1d(steps)
plt.figure(figsize=(10, 6))
plt.plot(range(steps), position)
plt.title("1D Random Walk")
plt.xlabel("Step")
plt.ylabel("Position")
plt.grid(True)
plt.show()
average_distance = np.mean(np.abs(position))
end_position = position[-1]
print(f"Average distance from start: {average_distance:.2f}")
print(f"End position: {end_position}")
As you can see in the chart above, the random walk simulation shows a fluctuation because each step is independent of the other. It’s similar to the stock price, where the price is fluctuating.
You can add more conditions to make your simulation suitable for your simulation. For example, the Brownian motion simulation could describe the random walk process as a continuous-time process instead of a discrete step, as in the previous example.
def brownian_motion(n, dt=0.1):
random_steps = np.random.normal(0, np.sqrt(dt), n)
position = np.cumsum(random_steps)
return position
The code above simulates Brownian motion. It’s similar to the Random walk process, but the steps are represented by continuous values. We can perform the simulation using the following code:
n = 1000
dt = 0.1
position = brownian_motion(n, dt)
time = np.linspace(0, n*dt, n)
plt.figure(figsize=(10, 6))
plt.plot(time, position)
plt.title("Brownian Motion")
plt.xlabel("Time")
plt.ylabel("Position")
plt.grid(True)
plt.show()
average_distance = np.mean(np.abs(position))
end_position = position[-1]
print(f"Average distance from start: {average_distance:.2f}")
print(f"End position: {end_position:.2f}")
The process simulation is similar to the Random walk, but we can see that the position values are smaller. This is because we are using the standard distribution values as the step. You can change the values to anything you need and the distribution it draws from as well.
That’s the simple simulation process we can do with NumPy. Let’s try out the more advanced technique, Monte Carlo.
Monte Carlo Methodology with NumPy
The basic principle of the Monte Carlo Method is that we use a random simulation process to solve problems that might be deterministic. For example, we could simulate credit risk by simulating their default behavior a massive number of times to get the distribution of the potential loss.
The most common Monte Carlo simulation is the pi estimation, which is visually intuitive and could demonstrate the Monte Carlo principle. Let’s try to estimate the pi number using NumPy.
import numpy as np
def pi_estimation(sample):
x = np.random.uniform(0, 1, sample)
y = np.random.uniform(0, 1, sample)
dis = np.sqrt(x**2 + y**2)
inside_circle = dis[dis
Output>> Estimated value of π: 3.140724
So, the code above would try to estimate the π value using a Monte Carlo simulation. We start by generating random numbers between 0 and 1, as much as the sample number we want to the variable x and y (coordinates). Then we take the Euclidean distance of the coordinates from the origin (0,0) to see if the values fall within a quarter circle of radius 1. We consider the point inside of the circle if the distance is less than 1. Then we calculate all the points that fall within the circle and divide by the sample number. Lastly, we estimate the pi by multiplying it by 4, as the circle we have is the quarter circle.
As you can see, the pi estimation result is close to the actual number of pi. If you keep increasing the sample number, it will become even closer to the actual pi values. This is how the Monte Carlo methodology works, as the method relies on the law of large numbers where the average result is close to the expected value with a higher number of samples.
Let’s try the Monte Carlo method to simulate the credit risk default rate. We would simulate the default rate with multiple loan samples over some time at a certain default probability.
import matplotlib.pyplot as plt
def simulate_credit_risk(num_loans, num_periods, default_prob):
defaults = np.zeros((num_loans, num_periods))
for loan in range(num_loans):
for period in range(num_periods):
if np.random.rand()
The simulation shows that the Default Rate decreases over a more extended period with a higher number of samples. You can use the code above to play around with the probability, samples, and period parameters to see how the default rate changes over time.
You can create your simulation with NumPy and use the Monte Carlo methodology to get the expected result of your experiment.
Conclusion
NumPy is a powerful Python package for mathematical and statistical calculations. Its usefulness is also essential in random process simulation. In this article, we have explored how to use NumPy to generate random numbers, simulate random processes, and simulate Monte Carlo methodology.
Cornellius Yudha Wijaya is a data science assistant manager and data writer. While working full-time at Allianz Indonesia, he loves to share Python and data tips via social media and writing media. Cornellius writes on a variety of AI and machine learning topics.
Transform your cleaning routine with the Shark AI Ultra Voice Control Robot Vacuum! This high-tech marvel boasts over 32,487 ratings, an impressive 4.2 out of 5 stars, and has been purchased over 900 times in the past month. Perfect for keeping your home spotless with minimal effort, this vacuum is now available for the unbeatable price of $349.99!
Don’t miss out on this limited-time offer. Order now and let Shark AI do the work for you!
Support Techcratic
If you find value in Techcratic’s insights and articles, consider supporting us with Bitcoin. Your support helps me, as a solo operator, continue delivering high-quality content while managing all the technical aspects, from server maintenance to blog writing, future updates, and improvements. Support Innovation! Thank you.
Bitcoin Address:
bc1qlszw7elx2qahjwvaryh0tkgg8y68enw30gpvge
Please verify this address before sending funds.
Bitcoin QR Code
Simply scan the QR code below to support Techcratic.
Please read the Privacy and Security Disclaimer on how Techcratic handles your support.
Disclaimer: As an Amazon Associate, Techcratic may earn from qualifying purchases.