程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Making random walk coordinate map with Python

編輯:Python
import matplotlib.pyplot as plt
from random import choice
class RandWalk:
# A class generating random walk 
def __init__(self, num_points=5000):
# Initialize random walk properties 
self.num_points = num_points
# All random walks begin with (0,0)
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
# Calculate all the points included in the random walk 
# Keep walking , Until the list reaches the specified length 
while len(self.x_values) < self.num_points:
# Determine the direction and the distance to go 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 step in place 
if x_step == 0 and y_step == 0:
continue
# Calculate the... Of the next point x Values and y value 
x = self.x_values[-1] + x_step
y = self.y_values[-1] + y_step
self.x_values.append(x)
self.y_values.append(y)
# Simulate multiple random walks 
while True:
rw = RandWalk(50000)
rw.fill_walk()
plt.style.use('classic')
fig, ax = plt.subplots(figsize=(15, 9)) # In inches 
point_number = range(rw.num_points)
ax.scatter(rw.x_values, rw.y_values, c=point_number, cmap=plt.cm.Blues, edgecolors='none', s=1)
# Highlight start and end points 
ax.scatter(0, 0, c='green', edgecolors='none', s=100)
ax.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100)
# Hide axis 
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
keep_running = input('Make another walk?(y/n):')
if keep_running == 'n':
break

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved