我正在玩随机游走,我有两点。 第一个是随机行走,第二个是试图逃离他的区域,由公式e ^( - t)给出,其中t是两点之间的距离。 在我看来,这不是一个困难的程序,但它需要大约一分钟来运行它有百分计算,所以我要求你帮我找到一些方法来加快它并向我解释。
import numpy as np
import matplotlib.pyplot as plt
def f(x, y, zx, zy):
return np.exp(-np.sqrt((x-zx)**2+(y-zy)**2))
x = y = np.linspace(-100, 100, 1000)
X, Y = np.meshgrid(x, y)
fig, ax = plt.subplots(1, 1, figsize=(12, 6))
#random picking first location for two points
loksx = [np.random.randn(), ]
loksy = [np.random.randn(), ]
lokzx = [np.random.randn(), ]
lokzy = [np.random.randn(), ]
for i in range(100):
lokzx.append(np.random.randn()+lokzx[-1])
lokzy.append(np.random.randn()+lokzy[-1])
nsx = np.random.randn()
nsy = np.random.randn()
#checking if the next step has smaller value than the last one
if f(loksx[-1]+nsx, loksy[-1]+nsy, lokzx[-1], lokzy[-1]) < f(loksx[-1], loksy[-1], lokzx[-1], lokzy[-1]):
loksx.append(nsx+loksx[-1])
loksy.append(nsy+loksy[-1])
Z = []
for i in range(len(lokzx)):
Z.append(f(X, Y, lokzx[i], lokzy[i]))
ax.plot(lokzx[0], lokzy[0], 'y,',markersize=1)
ax.plot(loksx[0], loksy[0], 'w,', markersize=1)
ax.plot(lokzx[1:-1], lokzy[1:-1], 'g,',markersize=1)
ax.plot(loksx[1:-1], loksy[1:-1], 'b,', markersize=1)
ax.plot(loksx[-1], loksy[-1], 'k,', markersize=1)
ax.plot(lokzx[-1], lokzy[-1], 'r,',markersize=1)
for i in range(len(Z)):
ax.contourf(X, Y, Z[i], 20, cmap='RdGy', alpha=0.01)
ax.plot()
ax.set_aspect('equal')
plt.show()
@edit现在而不是使用列表我正在使用nparrays:
import numpy as np
import matplotlib.pyplot as plt
def f(x, y, zx, zy):
return np.exp(-np.sqrt((x-zx)**2+(y-zy)**2))
x = y = np.linspace(-100, 100, 1000)
X, Y = np.meshgrid(x, y)
fig, ax = plt.subplots(1, 1, figsize=(12, 6))
lokzx = np.random.randn(100)
lokzy = np.random.randn(100)
loksx = np.zeros(100)
loksy = np.zeros(100)
for i in range(1,100):
nsx = np.random.randn()
nsy = np.random.randn()
if f(loksx[i-1]+nsx, loksy[i-1]+nsy, lokzx[i-1], lokzy[i-1]) < f(loksx[i-1], loksy[i-1], lokzx[i-1], lokzy[i-1]):
loksx[i] = loksx[i-1]+nsx
loksy[i] = loksy[i-1]+nsy
else:
loksx[i] = loksx[i-1]
loksy[i] = loksy[i-1]
Z = np.zeros((100,1000,1000))
for i in range(len(lokzx)):
Z[i] = f(X, Y, lokzx[i], lokzy[i])
ax.plot(lokzx[0], lokzy[0], 'y,',markersize=1)
ax.plot(loksx[0], loksy[0], 'w,', markersize=1)
ax.plot(lokzx[1:-1], lokzy[1:-1], 'g,',markersize=1)
ax.plot(loksx[1:-1], loksy[1:-1], 'b,', markersize=1)
ax.plot(loksx[-1], loksy[-1], 'k,', markersize=1)
ax.plot(lokzx[-1], lokzy[-1], 'r,',markersize=1)
for i in range(len(Z)):
ax.contourf(X, Y, Z[i], 20, cmap='RdGy', alpha=0.01)
ax.plot()
ax.set_aspect('equal')
plt.show()
但是仍然需要一段时间来运行它。 剩下的唯一问题是这两行代码:
for i in range(len(Z)):
ax.contourf(X, Y, Z[i], 20, cmap='RdGy', alpha=0.01)
但我不知道如何在不使用循环的情况下重写它。