我有以下問題:蟒蛇,scipy-功課 - 如何保持粒子的位置的歷史網格
創建一個程序,其中一個粒子將執行這兩個爲N = 1000步隨機遊走情況:i)在一維繫統中ii)在二維繫統中。 程序必須計算平均值(S),其中S是粒子訪問至少一次的網格位置數。您將進行10000次運行並找到10個點(每100步一次,從0到1000),其中將是10000次運行的手段。做平均值(S)相對於時間t的圖。
我這樣做代碼:
import scipy as sc
import matplotlib.pyplot as plt
import random
plegma=1000
grid=sc.ones(plegma) # grid full of available positions(ones)
for p in range(10000):
#-------------------Initialize problem-------------------------------------------------
his_pos=[] # list which holds the position of the particle in the grid
in_pos = int(sc.random.randint(0,len(grid),1)) #initial position of particle
means=[] #list which holds the means
#--------------------------------------------------------------------------------------
for i in range(0,1000,100):
step=2*sc.random.random_integers(0,1)-1 #the step of the particle can be -1 or 1
# Check position for edges and fix if required
# Move by step
in_pos += step
#Correct according to periodic boundaries
in_pos = in_pos % len(grid)
#Keep track of random walk
his_pos.append(in_pos)
history=sc.array(his_pos)
mean_his=sc.mean(history)
means.append(mean_his)
plt.plot(means,'bo')
plt.show()
修訂--------------------------------- ----
import scipy as sc
import matplotlib.pyplot as plt
import random
plegma=1000
his_pos=[] # list which holds the number of visited cells in the grid
means=[] #list which holds the means
for p in range(10000):
#-------------------Initialize problem-------------------------------------------------
grid=sc.ones(plegma) # grid full of available positions(ones)
in_pos = int(sc.random.randint(0,len(grid),1)) #initial position of particle
num_cells=[] # list which holds number of visited cells during run
#--------------------------------------------------------------------------------------
for i in range(1000):
step=2*sc.random.random_integers(0,1)-1 #the step of the particle can be -1 or 1
# Check position for edges and fix if required
# Move by step
in_pos += step
#Correct according to periodic boundaries
in_pos = in_pos % len(grid)
grid[in_pos]=0 # mark particle position on grid as "visited"
if (i+1) % 100 == 0:
number=1000-sc.sum(grid) # count the number of "visited positions" in grid
num_cells.append(number) # append it to num_cells
his_pos.append(num_cells) # append num_cells to his_pos
history=sc.array(his_pos)
mean_his=history.mean(1)
means.append(mean_his)
更新2 ----------------------------- .....
if (i+1) % 10 == 0:
number=1000-sc.sum(grid) # count the number of "visited positions" in grid
num_cells.append(number) # append it to num_cells
his_pos.append(num_cells) # append num_cells to his_pos
history=sc.array(his_pos)
mean_his=history.mean(0)
plt.plot(mean_his,'bo')
plt.show()
謝謝!
如果這是一個家庭作業的問題(它肯定看起來像一個),那麼請標誌是這樣。 – talonmies
「程序必須計算出其中的S是......」您可以重新編輯您的文本以使其可以理解嗎? – joaquin
@joaquin:好的,我編輯並更新了帖子。如果你能解釋我的話,我將不勝感激! – George