2014-10-07 17 views
-3
def evolve(): 
    global pop,fvals 
    for g in xrange(0,gmax):  
     for i in xrange(0,NP):   
      while 1: 
       r1=random.randint(0,NP-1) 
       if r1!=i:   
        break   
      while 1: 
       r2=random.randint(0,NP-1) 
       if r2!=r1 and r2!=i: 
        break 
      while 1: 
       r3=random.randint(0,NP-1) 
       if r3!=r2 and r3!=r1 and r3!=i: 
        break 
      U=[] 
      V=[] 
      for j in xrange(0,dim):  
        U.insert(j,(pop[r3])[j] + F*((pop[r1])[j]-(pop[r2])[j]))      
      jrand = floor(int(rand1()*dim)) 
      for j in xrange(0,dim): 
     if rand1()<=cr or j==jrand: 
        U.insert(j,(pop[r3])[j] + F*((pop[r1])[j]-(pop[r2])[j])) 
       else: 
        U.insert(j,(pop[i])[j])   
      V.insert(i,U)       
     fvals2.insert(i,fun(U)) 
     x=open("x.out","w")   
     for i in xrange(NP): 
      for j in xrange(dim): 
       print i 
      print j 
       x.write(str((V[i])[j]) + '\t') 
      x.write(str(fvals2[i])) 
      x.write('\n') 

雖然執行此代碼塊示出了一個錯誤:在exceuting下面的代碼獲得以下錯誤:索引超出範圍

x.write(str((V[i])[j]) + '\t') 
IndexError: list index out of range 

在這裏,我已經採取gmax=5dim=2NP=5

+0

列表「V」似乎少於'NP'元素。要麼在該循環中更改'i'範圍,要麼找出爲什麼'V'具有太少的元素。 – chepner 2014-10-07 14:41:45

回答

0

您正在將V設置爲[],因爲您的每個for n in xrange(0,NP)循環都丟失了以前的任何值。這意味着當你寫這個文件時,V只有一個值(最多),這就是爲什麼當你試圖從中讀取xrange(NP)值時,你會得到一個IndexError。您可能想要在該循環之外初始化V

你也錯過了if rand1()<=cr or j==rand的一些縮進,但是我猜這發生在將代碼放入帖子時發生,或者在編寫文件時可能沒有足夠的運行時間來獲得IndexError。

這且不說,請考慮以下因素:

  1. 請與實際的名稱命名變量 - 所有這些單字母和字母數字組合使代碼真的很難看。
  2. 您也可以考慮將這些嵌套操作中的一部分分解爲單獨的函數,這也可以提高可讀性。
  3. 完成寫操作後,您並未關閉輸出文件 - 您可能希望將x.close()行添加到末尾,或在with open('x.out','w') as x:塊中完成所有寫入。您還將覆蓋每個for g in xrange(0,gmax)的循環上的該文件,因此您可能還想將其移至該循環之外。