【问题标题】:Brownian motion in python 2Dpython 2D中的布朗运动
【发布时间】:2026-02-01 16:40:01
【问题描述】:

我想创建一个布朗运动模拟 我的粒子将从原点 (0,0) 开始,然后我为 x 和 y 方向创建了 NumPy 随机数组,例如 x = [-2,1,3] 和 y = [0,-2, 1]。由于粒子从原点(第 0 点)开始,它会在方向 -2 和 y (第 1 点)上移动 0 到下一个点,然后对于第 2 点,它将向右移动 1 个单位(+ x) 中的 1 个单位和左侧的 -2 个单位(y 中的 -2 个单位)。 我的问题是我将如何做到这一点,以便每个点都充当新的原点,就像添加向量一样。我想我需要某种 for 循环,但不确定如何设置它。

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()

这是我目前所拥有的。任何帮助表示赞赏。

【问题讨论】:

标签: python numpy random


【解决方案1】:

您需要从(0,0) 开始走N 步骤。使用变量prev = [0,0] 跟踪您的步骤,并为每个步骤进行更改。简化代码:

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]

【讨论】:

    【解决方案2】:

    您似乎希望绘制整个步行过程,只需将所有这些步骤相加即可?

    origin = np.array([0, 0])
    
    x_series = np.cumsum(dx) + origin[0]
    
    # (Similarly for y)
    

    这仅适用于 1 个随机游走者。如果您有多个随机游走者 - 每个人都有一个起点和独立的dx-s 链。

    【讨论】: