In this article, we share the specific code of Python3 random walk to generate data and plot for your reference, the details are as follows
random_walk.py
from random import choice # Generate data classes for random walks class RandomWalk(): def __init__(self,num_points=5000): # Initialize random walk properties =num_points # Default points for random walks self.x_values=[0] # All random walks start at (0.0) self.y_values=[0] def fill_walk(self): while len(self.x_values)<: # Determine the direction of travel 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 # Refuse to stand still if x_step==0 and y_step==0: continue # Calculate the x and y values for the next point next_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)
rw_visual.py
import as plt from random_walk import RandomWalk # Create a RandomWalk instance and plot all the points it contains rw = RandomWalk() rw.fill_walk() (rw.x_values, rw.y_values, s=15) # Redraw start and end points (highlight start and end points) (0,0,c='green',edgecolors='none',s=100) (rw.x_values[-1],rw.y_values[-1],c="red",edgecolors='none',s=100) #Hide the axes ().get_xaxis().set_visible(False) ().get_yaxis().set_visible(False) # Set the screen resolution and size of the window (dpi=128,figsize=(10,6)) ()
Result graph:
This is the whole content of this article.