# Sharing some programming knowledge.

0%

## Random Walk

A `random walk` is the process by which randomly-moving objects wander away from where they started. There are many kinds of Random Walk, but we only consider `Lattice Random Walk Problem` in this article, which simply assumes the object is walking on a lattice.

## Matplotlib

Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. (from Matplotlib Documentation)

Simply put, it is one of python’s mathematical drawing libraries that can output figures based on input datas. Its function is similar to MATLAB. To install it, use `pip install matplotlib`.

## Basic Usages of Matplotlib

Below are some basic usages of matplotlib that we will encounter in our Random Walk Program.

• Basic Methods:
• Import module `pyplot`: `import matplotlib.pyplot as plt`
• Use `plt.plot(x_values, y_values)` to generate line graphs based on the given parameter, x_values and y_values are 2 lists.
• Use `plt.scatter(x_values, y_values)` to generate scatter diagrams
• Use `plt.show()` to display figures.
• Use `plt.savefig('path')` to save figures.
• Customize the figure:
• Add title: `plt.title("title", fontsize=20)`
• Add label to axes: `plt.xlabel("x", fontsize=14)` and `plt.ylabel("y", fontsize=14)`
• Hide axes: `plt.axes().get_xaxis().set_visible(False)` and `plt.axes().get_yaxis().set_visible(False)`
• Change the width of the line: `plt.plot(list1, list2, linewidth=5)`
• Change the size of tick label: `plt.tick_params(axis='both', labelsize=14)`
• Change the size of the dot: `plt.scatter(x_values, y_values, s=200)`
• Add color to dots: `plt.scatter(x_values, y_values, s=200, c='red')`
• Use color map:

## 2D Random Walk Implementation

Run the program, and we will get something beautiful like this: It will vary every time. It’s quite interesting to see how it varies and what pattern it will produce.

Note that, roughly, the average distance between the start point and the end point is `R*sqrt(N)` where R is the average step-length and sqrt(N) is the square root of the number of steps.

What’s more, about lattice random walk problems, it’s interesting to think about that “What’s the probability that it’ll end up going through the starting point again?” Mathematicians have calculated the answers:

Dimension probability
1 100
2 100
3 34.0537
4 19.3206
5 13.5178
6 10.4715
7 8.58449
8 7.29126
( the data is from Pólya’s Random Walk Constants )

Though it’s glad to see that a drunken man would eventually find his way home, in most cases he will probably have to walk far more than 1 million steps to get home. ( After 1 million steps, he is still far from his home. ) ( woooh, it only takes him 3826 steps! )

## A try for 3D Random Walk Implementation

Of course, we could also try it on 3D lattice.
Just simply import `Axes3D`

But I didnl’t get anything exciting: ( It starts from yellow to blue. )