2014-12-03 2 views
0

파이썬으로 2D 랜덤 워크를 만들려고합니다. 무작위 걸음은 사각형 내에서 발생하며, 입자가 사각형의 어느 한면을 교차하면 입자가 다른면에 나타납니다. 사실상 무작위 도보는 토러스에서 발생합니다.파이썬으로 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") 

이 코드는 다음과 같은 플롯을 생성합니다 : 여기

내 코드의 사본의 입자가 측면 중 하나가 내가이 '줄무늬를 얻을 교차 할 때마다 enter image description here

당신이 볼 수 있듯이, 플롯에서 plot()은 멀리 떨어져 있어도 두 점을 연결하기 때문입니다. 이런 일이 발생하지 않도록하는 방법이 있습니까?

+0

) 아마도 그것을 수동으로해야 할 것입니다. (예를 들어 연속적인 조각을 나누어 따로 따로 처리하십시오.) - 플로팅 코드는 불연속 점을 알 수있는 방법이 없습니다. – Ajean

+2

랩 어라운드 코드를 수행하는 두 시리즈 모두에 'np.nan'을 던질 수도 있습니다. – tacaswell

답변

3

나는 또한 읽기 (내 생각에) 쉽게 확인하기 위해 steping 코드를 조금 다시 쓴 : 그들은 플로트 사양의 일부입니다 np.nan (숫자를 가하고 있습니다

from random import randrange as rand 
from numpy import cos, sin, radians 
import numpy as np 
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. 

def wrap(v, N): 

    if v > N/2: 
     return v - N, True 
    elif v < -N/2: 
     return v + N, True 
    return v, False 


for j in range(NSteps): 
    angle = radians(rand(361)) 
    x, wrap_flag_x = wrap(x + cos(angle), N) 
    y, wrap_flag_y = wrap(y + sin(angle), N) 
    if wrap_flag_x or wrap_flag_y: 
     xList.append(np.nan) 
     yList.append(np.nan) 
    xList.append(x) 
    yList.append(y)  

fig, ax = plt.subplots() 
ax.plot(xList,yList,c="b") 
ax.set_xlim(-N/2,N/2) 
ax.set_ylim(-N/2,N/2) 
ax.get_xaxis().set_visible(False) 
ax.get_yaxis().set_visible(False) 

을)를 귀하의 목록에 추가하십시오. mpl이 선을 그릴 때 기본 선 스타일을 사용하여 모든 점을 연결합니다. np.nan 인 점은 마지막 점에서 np.nan 점까지의 선이 그려지지 않으므로 np.nan에서 다음 점까지 선이 그려지지 않으므로 선이 끊어집니다. 보조 노트로 output

,이 시뮬레이션의 대부분은 벡터화 할 수 있습니다

from numpy.random import randint 
from numpy import cos, sin, radians, cumsum 
import numpy as np 
import matplotlib.pyplot as plt 

N = 100 # Size of square as a multiple of the step size. 
NSteps = 5000 # Number of steps in simulation. 
x_start = 0 # x coordinate of starting location. Origin is at centre of square 
y_start = 0 # y coordinate of starting location. Origin is at centre of square 



# get all of the angles 
angles = radians(randint(low=0, high=361, size=NSteps)) 

# get (unwrapped) positions 
x = cumsum(cos(angles)) + x_start 
y = cumsum(sin(angles)) + y_start 

# find where the position crosses the boundary 
x_wraps = np.where(np.diff((x + N/2) // N))[0] 
y_wraps = np.where(np.diff((y + N/2) // N))[0] 

# do the wrapping 
x = x - N * ((x + N/2)//N) 
y = y - N * ((y + N/2)//N) 

나는 독자들에게 운동으로 NaN을 삽입하기 위해 랩 위치를 사용하여두고, 내가 당신을 추측 할

+0

멋진 답변을 해 주셔서 감사합니다.하지만 불행히도 어떻게 작동하는지 이해하지 못합니다! 'xList.append (np.nan)'과'yList.append (np.nan)'은 정확히 무엇을하고 있습니까? –

+1

수정 사항을 참조하십시오. – tacaswell

관련 문제