Random walks are mathematical models that depict a
The walker’s current position serves as the starting point for each step, and based on a random decision, the walker moves to a new position.
So the big question is, what do we exactly mean by randomness here?
Well, the randomness in a random walk refers to the uncertainty in determining the direction or the distance of the steps. That means our walker can move in different directions, including forward, backward, left, or right, depending on the settings we’ve applied to the walk.
Note: This exact randomness inherent in random walks is what makes them great for modeling various real-world phenomena that involve uncertainty or
b stochastic outcomes that are based on probability ehavior. outcomes that are based on probability
Random walks can take on various forms. Let’s discuss two common types:
Simple random walk | Lattice random walk |
Only discrete steps are considered in this type of walk. Easily put, the steps in the walk can be in one of the two directions (+1 or -1) with equal probability. | This walk is a little different, and here the steps are taken along the grid or lattice lines. |
The walk can either have discrete or continuous steps.
Discrete: The walker moves step by step in discrete walks.
Continuous: The walker moves smoothly in a continuous space.
The step sizes in random walks can follow different probability distributions, like:
Gaussian
Uniform
Random walks can also have rules for directional randomness. For instance:
Isotropic: Equal probability in all directions.
Anisotropic: Direction-dependent probabilities.
Having gone through the core concepts behind random walks, let's now implement a random 3D walk using Python's library Matplotlib.
import numpy as npimport matplotlib.pyplot as pltimport matplotlib.animation as animation
First and foremost, we import the modules required for this implementation. numpy
is used for operations on numbers and matplotlib
for plots as well as animations.
distanceOfStep = 0.1
We define distanceOfStep
as the maximum distance of each step in our random walk.
walk3DRandom
methoddef walk3DRandom(stepsPerWalk):randomStart = np.random.random(3)generateSteps = np.random.uniform(-distanceOfStep, distanceOfStep, size = (stepsPerWalk, 3))generateWalk = randomStart + np.cumsum(generateSteps, axis = 0)return generateWalk
For generating our 3D random walk, we define the walk3DRandom
function and pass the number of steps as a parameter.
randomStart
assigns a random starting position in 3D space using np.random.random(3)
.
generateSteps
generates random step sizes within the range of distanceOfStep
using np.random.uniform(-distanceOfStep, distanceOfStep, size=(stepsPerWalk, 3))
.
generateWalk
calculates the cumulative sum of the step sizes to obtain the coordinates of the random walk.
We return the generateWalk
array.
updatePaths
methoddef updatePaths(frameNum, listOfWalks, listOfLines):for path, trajectory in zip(listOfLines, listOfWalks):path.set_data(trajectory[:frameNum, :2].T)path.set_3d_properties(trajectory[:frameNum, 2])return listOfLines
For updating the positions of the lines for each frame, updatePaths
is defined. We pass frameNum
as the current frame number, listOfWalks
as the list of random walks, and listOfLines
as the list of line objects representing the walks.
The for
loop iterates over both listOfLines
and listOfWalks
simultaneously using zip
.
Inside the loop, we use path
to refer to the current line object and trajectory
to refer to the current random walk.
The line path.set_data(trajectory[:frameNum, :2].T)
updates the
The line path.set_3d_properties(trajectory[:frameNum, 2])
updates the
We finally return the listOfLines
, now containing the updated line objects.
Note: The zip method takes iterables as a parameter and then returns iterators for it.
stepsPerWalk = 40walks = [walk3DRandom(stepsPerWalk) for i in range(50)]
stepsPerWalk
represents the number of steps in each random walk. We can customize it according to our needs. On the other hand, walks
is a list that generates 50 random walks using the walk3DRandom
method we just created above.
figure = plt.figure()ax = figure.add_subplot(projection = "3d")
We create a figure
and a 3D subplot ax
using plt.figure()
and figure.add_subplot(projection=“3d”)
, respectively.
lines = [ax.plot([], [], [])[0] for _ in walks]
We initialize the lines as empty line objects initially.
animationOfWalks = animation.FuncAnimation(figure, updatePaths, stepsPerWalk, fargs = (walks, lines), interval = 150)
Onto the most exciting part!
To render the animation, we create the animationOfWalks
using animation.FuncAnimation
. This method takes the figure, the update function updatePaths
, the total number of frames stepsPerWalk
, and lastly, walks
and lines
within fargs
interval
between the frames as 150 milliseconds (susceptible to change).
plt.show()
To see our animation, we use plt.show()
to display the animation plot.
Having covered the building blocks of our 3D random walk using Matplotlib, let's now join the pieces together and run our code!
The following code will result in an output of our 3D random walk-through GUI. Click on the "run" button to see the output in the "output" tab.
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation distanceOfStep = 0.1 def walk3DRandom(stepsPerWalk): randomStart = np.random.random(3) generateSteps = np.random.uniform(-distanceOfStep, distanceOfStep, size = (stepsPerWalk, 3)) generateWalk = randomStart + np.cumsum(generateSteps, axis = 0) return generateWalk def updatePaths(frameNum, listOfWalks, listOfLines): for path, trajectory in zip(listOfLines, listOfWalks): path.set_data(trajectory[:frameNum, :2].T) path.set_3d_properties(trajectory[:frameNum, 2]) return listOfLines stepsPerWalk = 40 walks = [walk3DRandom(stepsPerWalk) for i in range(50)] figure = plt.figure() ax = figure.add_subplot(projection = "3d") lines = [ax.plot([], [], [])[0] for _ in walks] animationOfWalks = animation.FuncAnimation(figure, updatePaths, stepsPerWalk, fargs = (walks, lines), interval = 150) plt.show()
Since our walk will show different steps at different frames and increase slowly, let's observe the output at various times of the animation.
Physics and chemistry: Simulating particle movements and diffusion in molecular dynamics and understanding the spread of substances or heat in physical systems.
Financial modeling: Predicting stock prices and exchange rates based on the unpredictable as well as random nature of market movements.
Biology and genetics: Modeling the movement of organisms and particles in biological systems. We could even use this in observing the spreading of genetic traits through populations.
Image analysis and computer graphics: Segmenting images into distinct regions and creating animations of objects in computer graphics.
Optimization and sampling: Exploring search spaces and finding optimal solutions using random sampling techniques.
Random walks in Markov chains: Random walks are pivotal in studying Markov chains. These are basically mathematical models to describe systems that transition between states.
While the examples discussed earlier focus on 3D random walks, random walks can also be extended to higher dimensions, such as 4D or even higher-dimensional spaces. Higher-dimensional random walks can find applications in physics, finance, and optimization.
Let’s have a pop quiz on our 3D Random Walk!
How does path.set_data(trajectory[:frameNum, :2].T)
set both X and Y coordinates in a single statement?
Using the T method.
Using the frame number.
The set_data method takes care of it.
:2 does the slicing to obtain both values.
Free Resources