"Python" Random walk

Source: Internet
Author: User

Create Randomwalk () class

We'll use Python to generate random walk data, and then use Matplotlib to bring this data to life in a compelling way.

First create the class Randomwalk ()

 fromRandomImportChoiceclassRandomwalk ():" "A class that generates random walk data" "    def __init__(self,num_points=5000):        " "Initialize the attributes of a random walk" "self.num_points=num_points#all random walks start at (0,0)Self.x_values =[0] self.y_values=[0]defFill_walk (self):" "calculate all points of a random walk" "        #walk continuously until the list reaches the specified length         whileLen (self.x_values) <self.num_points:#to determine the direction of the move and the distance in that direction.x_direction = Choice ([1,-1]) x_distance= Choice ([0,1,2,3,4]) X_step= x_direction*x_distance y_direction= Choice ([1,-1]) y_distance= Choice ([0, 1, 2, 3, 4]) Y_step= Y_direction *y_distance#refusing to tread            ifX_step = = 0 andY_step = =0:Continue            #calculates the x and Y values of the next pointnext_x = self.x_values[-1]+X_step next_y= Self.y_values[-1] +y_step self.x_values.append (next_x) self.y_values.append (next_y)

__init__ () and Fill_walk (), where the latter calculates all points passing through a random stroll.

We use choice ([1,-1]) to select a value for direction, the result is either to walk to the right 1, or to go to the left-1, Next, Choice ([0,1,2,3,4]) randomly select an integer between 0~4, Tells Python how far to go along the specified direction (x_distance)

Draw a random walk chart
Import Matplotlib.pyplot as Plt  from Import Randomwalk # Create a Randomwalk instance and draw the points it contains RW = randomwalk () rw.fill_walk ()print(rw.x_values) Plt.scatter (rw.x_values,rw.y_values,s=15) plt.show ()

Operation Result:

We first import the modules Pyplot and Randomwalk classes, then we create an instance and store it in RW, then call Fill_walk (), we pass the random walk x and Y values to scatter (), and select the appropriate point size, Displays a random stroll with 5,000 points.

Simulate multiple random walks
ImportMatplotlib.pyplot as Plt fromMatplotlib_test.random_walkImportRandomwalk#as long as the program processes the active state, the random simulation is constantly whileTrue:#Create a Randomwalk instance and draw the points it containsRW =Randomwalk () Rw.fill_walk () Plt.scatter (Rw.x_values,rw.y_values,s=15) plt.show () keep_running= Input ("Make another walk? (y/n):")    ifKeep_running = ='N':         Break

The code simulates a random walk, which displays the results in the Matplotlib viewer and pauses without closing the viewer. If you close the viewer, the program asks if you want to simulate a random walk again, and if you enter Y, you will continue, and if you enter N, you will exit.

Set a random walk chart style

1. Coloring points

We use color maps to indicate the order of points, and to remove the black outlines of each point, to make their colors more visible, to color them according to the order of the points in the walk, we pass the parameter C and set it to a list that contains the order of the points.

Operation Result:

2. Redraw the start and end points

To highlight the beginning and the end, we can do this.

Operation Result:

3. Hide Axes

To modify the axes, use the function plt.axes () to set the visibility of the axes to false

Operation Result:

4. Add points

Let's increase the number of points and increase the value of num_points when creating Randomwalk instances

Operation Result:

5. Resize the window size

When the chart fits the screen size, it is more efficient to present the laws in the data

The window becomes noticeably larger

If you know your system's resolution, you can also use the parameter DPI to pass the resolution

Plt.figure (dpi=128,figsize= (10,6))

"Python" Random walk

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.