三维随机漫步返回原点的概率



这是我的代码模拟代码在python中模拟三维随机行走。它返回一个百分比乘以步行返回原点。在三维空间中,行走返回原点的概率为~ 34%。我的比例只有11% -12%。如果我乘以3(作为猜测),答案变得非常接近Polya常数,但大多数时候看起来更接近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

我将此作为蒙特卡罗模拟问题来处理;进行大量的随机漫步,看看在大量的步骤中返回原点的比例是多少。最简单的实现是一个函数执行一次遍历,另一个函数执行重复遍历。

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

stepsrepeats变得越大(即我们越接近"真实"情况,所有可能的行走都有无限的步数),我期望的输出变异性越小。对于显示的数字,我得到:

[0.33, 0.36, 0.34, 0.35, 0.34, 0.29, 0.34, 0.28, 0.31, 0.36]

最新更新