【发布时间】:2014-12-03 22:24:12
【问题描述】:
我正在尝试使用 Python 创建 2D 随机游走。随机游走发生在正方形内,如果粒子穿过正方形的任何一侧,粒子就会出现在另一侧——实际上,随机游走发生在圆环上。
这是我的代码的副本:
from random import randrange as rand
from math import cos, sin, radians
import matplotlib.pyplot as plt
N = 100 # Size of square as a multiple of the step size.
NSteps = 5000 # Number of steps in simulation.
xStart = 0 # x coordinate of starting location. Origin is at centre of square
yStart = 0 # y coordinate of starting location. Origin is at centre of square
s = 1 # Step number.
x = xStart # x coordinate of point.
y = yStart # y coordinate of point.
xList = [] # List of the x coordinates of all points visited.
yList = [] # List of the y coordinates of all points visited.
while s <= NSteps:
angle = radians(rand(361))
x += cos(angle)
if x > N/2:
x -= N
elif x < -N/2:
x += N
xList += [x]
y += sin(angle)
if y > N/2:
y -= N
elif y < -N/2:
y += N
yList += [y]
s += 1
plt.figure(figsize=(13,8))
frame = plt.gca()
plt.plot(xList,yList,c="b")
plt.xlim(-N/2,N/2)
plt.ylim(-N/2,N/2)
frame.axes.get_xaxis().set_visible(False)
frame.axes.get_yaxis().set_visible(False)
plt.savefig("randomWalk.png", bbox_inches="tight")
此代码生成如下图:
如您所见,每当粒子穿过其中一侧时,我都会在图上看到这些“条纹”,因为plot() 将连接两个点,无论它们相距多远。有没有办法防止这种情况发生?
【问题讨论】:
-
我猜你可能不得不手动完成(例如,分割连续的步行部分并分别绘制它们) - 绘图代码无法知道不连续性在哪里。跨度>
-
您也可以将
np.nan扔到您执行环绕代码的两个系列中。
标签: python python-3.x matplotlib