简体   繁体   中英

Brownian motion in python 2D

I want to create a Brownian motion sim My particle will start at the (0,0), the origin then I've created NumPy random arrays for the x and y direction for example, x = [-2,1,3] and y = [0,-2,1]. Since the particle starts at the origin (0th point) it will to the next point by -2 in the direction and 0 in the y (the 1st point), and then for the 2nd point, it will 1 unit to the right (+1 in the x) and -2 units to the left(-2 in the y). My question is how would I make it so each point acts as the new origin kind of like adding vectors. I'm thinking I would need some sort of for loop, but not sure how I would set it up.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation as am
np.random.seed(69420)
N=1000 #Number of steps
# Have the particle at the origin in 2D (x,y) plane
# Each step will have a lenght of 1 unit. Lets call it meters
# Each step is one second
# And this simulation will run for 100 seconds
## Now how to make a particle randomly walk???
t=100 # time interval
dt=t/N # delta time from each step
dx = np.random.randint(-5,5,N,dtype=int)# This would be our detla x for each step
dy = np.random.randint(-5,5,N,dtype=int)
dx_0 = np.zeros(N, dtype=int)
dy_0 = np.zeros(N,dtype=int)
X = dx_0+dx
Y = dy_0+dy
print(X)
xdis = np.cumsum(X)  #Total distance travled after N steps
ydis = np.cumsum(Y)
plt.plot(dx_0,dy_0,'ko')
plt.plot(xdis,ydis,'b-')
plt.show()

This is what I have so far. Any help is appreciated.

You need to take N steps, starting from (0,0) . Track your steps using a variable prev = [0,0] , and make changes to it for each step. Simplified code:

prev = [0,0]
for i in range(N):
    new_x = prev[0]+dx[i]
    new_y = prev[1]+dy[i]
    # do what you need with new_x and new_y
    prev = [new_x, new_y]

Since it seems like you wish to graph the entire walk, just sum all these steps?

origin = np.array([0, 0])

x_series = np.cumsum(dx) + origin[0]

# (Similarly for y)

This is only for 1 random walker. If you have multiple random walkers - each of them will have a starting point and separate chain of dx -s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM