三维随机行走回到原点的概率
这是我用Python写的代码,模拟一个在三维空间中随机行走的过程。它会返回这个行走回到起点的概率百分比。根据波利亚常数,三维空间中随机行走回到起点的概率大约是34%。而我计算出来的概率只有11%到12%。如果我把这个结果乘以三(只是个猜测),那么结果就会比较接近波利亚常数,但大多数时候看起来更接近36%。请告诉我在我的数学、逻辑或代码中有什么错误。谢谢!
def r3walk(T):
x = np.zeros((T))
y = np.zeros((T))
z = np.zeros((T))
count = 0
for t in range(1,T):
walk = random.uniform(0.0,1.0)
if 0 < walk < 1/float(6):
x[t] = x[t-1] + 1
elif 1/float(6) < walk < 2/float(6):
x[t] = x[t-1] - 1
elif 2/float(6) < walk < 3/float(6):
y[t] = y[t-1] + 1
elif 3/float(6) < walk < 4/float(6):
y[t] = y[t-1] - 1
elif 4/float(6) < walk < 5/float(6):
z[t] = z[t-1] + 1
else:
z[t] = z[t-1] - 1
for t in range(1,T):
if [x[t],y[t],z[t]] == [0,0,0]:
count += 1
return count/float(T)
编辑后的代码:
def r32walk(T):
x = np.zeros((T))
y = np.zeros((T))
z = np.zeros((T))
count = 0
for t in range(1,T):
walk1 = random.uniform(0.0,1.0)
if walk1 > 0.5:
x[t] = x[t-1] + 1
else:
x[t] = x[t-1] - 1
for t in range(1,T):
walk2 = random.uniform(0.0,1.0)
if walk2 > 0.5:
y[t] = y[t-1] + 1
else:
y[t] = y[t-1] - 1
for t in range(1,T):
walk3 = random.uniform(0.0,1.0)
if walk3 > 0.5:
z[t] = z[t-1] + 1
else:
z[t] = z[t-1] - 1
for t in range(1,T):
if [x[t],y[t],z[t]] == [0,0,0]:
count += 1
#return x,y,z
return count/float(T) * 100
1 个回答
2
我把这个问题看作是一个蒙特卡洛模拟的问题;也就是说,进行很多次随机走动,然后看看有多少比例在经过一定步数后能回到起点。最简单的做法是写一个函数来完成一次走动,另一个函数来重复这个过程。
import random
def simulation(dimensions, repeats, steps):
"""Simulate probability of returning to the origin."""
return sum(random_walk(dimensions, steps)
for _ in range(repeats)) / float(repeats)
def random_walk(n, s):
"""Whether an n-D random walk returns to the origin within s steps."""
coords = [0 for _ in range(n)]
for _ in range(s):
coords[random.randrange(n)] += random.choice((1, -1))
if not any(coords):
return True
return False
print [simulation(3, 100, 1000) for _ in range(10)]
当steps
(步数)和repeats
(重复次数)变得越来越大时(也就是我们越接近“真实”的情况,所有可能的走动和无限步数),我预期输出的结果会变得更稳定,不会有太大的波动。对于我得到的数字来说,结果是:
[0.33, 0.36, 0.34, 0.35, 0.34, 0.29, 0.34, 0.28, 0.31, 0.36]