这是我的代码模拟python中的代码,模拟3维随机游走。它返回步行返回原点的百分比。 Polya的常数是步行返回原点的概率约为34%。我的百分比只有11-12%。如果我乘三(作为猜测),答案变得非常接近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
答案 0 :(得分:2)
我将此视为Monte Carlo模拟问题;进行大量随机游走,并查看在一些大量步骤中返回原点的比例。最简单的实现是一个单独步行的功能,另一个是重复执行。
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
越大(即越接近&#34;真实&#34;情况,所有可能的步行都有无数步骤),变化越小我预期的输出。对于显示的数字,我得到:
[0.33, 0.36, 0.34, 0.35, 0.34, 0.29, 0.34, 0.28, 0.31, 0.36]