Free learning recommendation: python video tutorial
Random Walk
This time we will use python to generate random walk data, and then use matplotlib to present the data.
Each walk in a random walk is completely random, with no clear direction, and the result is determined by a series of random decisions. You can think of it this way, a random walk is the path that ants take in a random direction every time when they are confused.
Create the RandomWalk() class
In order to simulate a random walk, we create a RandownWalk class that randomly chooses the direction to move forward. This class requires three attributes, one of which is a variable that stores the number of random walks, and the other two are lists that store the x-coordinates and y-coordinates of each point passed by the random walk.
The RandomWalk class contains only two methods, init() and fill_walk(), where the latter calculates all points passed by the random walk. The following is __init__()
:
from random import choiceclass RandomWalk(): """一个生成随机漫步数据的类""" def __init__(self, number_points=5000): """初始化随机漫步的属性""" self.number_points = number_points # 所有随机漫步都始于(0,0) self.x_values = [0] self.y_values = [0]
To make a random decision, we store all possible choices into a list and use choice() every time we make a decision to decide which choice to use, then we take the random walk The default number of points is set to 5000, and then we create two lists to store x values and y values, and let each walk start from (0,0).
Select a direction
def fill_walk(self): """计算随机漫步中包含的所有点""" # 不断漫步,直到列表达到指定的长度 while len(self.x_values) <p> We establish a loop that continues until the walk contains all the required number of points. The main part of this method tells python how to simulate four wandering decisions: go left or right? Going up or down? How far along the given direction? <br> We use choice([1, -1]) to select a value for x_direction. The result is either 1, which means going right, or -1, which means going left. Next, choice([0, 1, 2 , 3, 4]) Randomly select a number between 0 and 4 to tell python how far to go in the specified direction. <br> We multiply the direction of movement by the distance of movement to determine the distance moved along the x- and y-axes. If x_step is positive, it will move to the right, if it is negative, it will move to the left, and if it is 0, it will move vertically, if y_step is positive, it will move up, if it is negative, it will move down, if it is 0, it will move horizontally, if both are 0, then Thinking that we are standing still, we reject this situation and continue the next cycle. <br> To get the x value of the next point in the random walk, we add the last value of x_step and x_values, and do the same for the y value. After getting the x-value and y-value of the next point, we append it to the end of the lists x_values and y_values respectively. </p><p><strong>Drawing a random walk graph</strong></p><p>We named the py file that created the RandomWalk class above random_walk.py. <br> The following code plots all points of the random walk: </p><pre class="brush:php;toolbar:false">import matplotlib.pyplot as pltfrom random_walk import RandomWalk# 创建一个RandWalk实例,并将其包含的点都绘制出来rw = RandomWalk(5000)rw.fill_walk()plt.scatter(rw.x_values, rw.y_values, s=15)plt.show()
We first imported the module pyplot and the RandomWalk class, then created a RandomWalk instance, stored it in rw, and then called fill_walk(), the following figure shows a random walk graph containing 5000 points.
Simulate multiple random walks
Every random walk is different, so it’s fun to explore the various patterns that might be generated. One way to use the previous code to simulate multiple random walks without running the program multiple times is to put the previous code into a while loop, as shown below:
import matplotlib.pyplot as pltfrom random_walk import RandomWalkwhile True: # 创建一个RandWalk实例,并将其包含的点都绘制出来 rw = RandomWalk(5000) rw.fill_walk() plt.scatter(rw.x_values, rw.y_values, s=1) plt.show() keep_running = input('Make another walk? (y/n) : ') if keep_running == 'n': break
These codes simulate a random walk Walk, if you enter y, you will continue to simulate and generate a random walk. If you enter n, you will exit the program.
Color the points
We will use color to map the order of the points in the walk, and delete the black outline of each point to make their colors more obvious. To color according to the order of the points in the walk, we pass the parameter c and set up a list containing the order of the points. Since these points are drawn in order, the list specified by parameter c only needs to contain numbers 1~5000. As shown below:
import matplotlib.pyplot as pltfrom random_walk import RandomWalkwhile True: # 创建一个RandWalk实例,并将其包含的点都绘制出来 rw = RandomWalk(5000) rw.fill_walk() point_numbers = list(range(rw.number_points)) plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolors='none', s=1) plt.show() keep_running = input('Make another walk? (y/n) : ') if keep_running == 'n': break
We use range to generate a list of numbers that contains the same number of points as the walk contains. Next, we store this list into point_numbers so that we can use it to set the color of each walk point. We set each parameter c to point_numbers, specify the color map to be blue, and pass the argument edgecolors to remove the outline around each point. The final random walk graph gradients from light blue to dark blue. As shown in the figure below:
Redraw the starting point and end point
In addition to coloring the random walk points to indicate their order, It would be better if we could also show the end and starting point of the random walk. To do this, you can redraw the start and end points of the random walk after drawing the random walk diagram. We made the start and end points larger and a different color to highlight them, like this:
import matplotlib.pyplot as pltfrom random_walk import RandomWalkwhile True: # 创建一个RandWalk实例,并将其包含的点都绘制出来 rw = RandomWalk(5000) rw.fill_walk() point_numbers = list(range(rw.number_points)) plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolors='none', s=1) # 突出起点和终点 plt.scatter(0, 0, c='green', edgecolors='none', s=100) plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100) plt.show() keep_running = input('Make another walk? (y/n) : ') if keep_running == 'n': break
为突出起点,我们使用绿色绘制点(0,0),并使其比其它点大。为突出终点,我们在漫步包含的最后一个x值和y值处绘制一个点,使其为红色,并比其它点大。运行代码,将准确知道每次随机漫步的起点和终点。
隐藏坐标轴
下面来隐藏坐标轴,以免我们注意点是坐标轴而不是随机漫步路径。要隐藏坐标做代码如下:
# 隐藏坐标轴plt.axes().get_xaxis().set_visible(False)plt.axes().get_yaxis().set_visible(False)
为修改坐标轴,使用函数plt.axes()来将每条坐标轴的可见性设置为False。图如下:
相关免费学习推荐:python教程(视频)
The above is the detailed content of python random walk explanation. For more information, please follow other related articles on the PHP Chinese website!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools