2011-03-02 83 views
0

我對python比較陌生,對我的物理大學課程做了一點。Python索引超出範圍錯誤,不知道我在做什麼錯誤

目前我正在嘗試編寫一個程序來計算一些與矢量函數有關的東西,但這並不重要,因爲我已經將所有東西都處理到最後一節。

到目前爲止,程序在2D圖上產生局部最小值的負載,但是我需要找到整體的最小值。

for i in range(100): 
    pyplot.xlim(x0, x1) # x0, y0 etc are constants defined before in global scope 
    pyplot.ylim(y0, y1) 
    pyplot.plot(min_points[:,0], min_points[:,1]) 
    x, y = random.uniform(x0, x1), random.uniform(y0, y1) 
    min_points = gradient_descent((x,y)) # gradient_descent is function used 

    xmin_list, ymin_list = [], [] # now to find overall minima, initialise list 
            # of local minima, and append those that are within 
            # the boundaries 
    if x0 < min_points[-1, 0] < x1: 
     if y0 < min_points[-1, 1] < y1: 

      xmin_list.append(min_points[-1, 0]) 
      ymin_list.append(min_points[-1, 1]) 

    xmin, ymin = xmin_list[0], ymin_list[1] # < error comes in this line 

我已經包括了對大低於完整性循環的其餘部分,但它不是有點給我一個錯誤(還)。

for ix in range(len(xmin_list)): 
     for iy in range(len(ymin_list)): 
      if f((xmin_list[ix], ymin_list[iy])) < f((xmin, ymin)): 
       xmin, ymin = xmin_list[ix], ymin_list[iy] 

所以這顯然是圍繞整個循環的中間,但我不知道爲什麼我得到的錯誤。我試圖訪問每個列表的最後一個元素,然後將它們追加到列表中(在檢查符合條件x0,x1等之後)。

我不知道爲什麼它不工作..

我也知道這是要去關於發現的最小一個相當複雜的方式,但它似乎合乎邏輯的我,我感到困惑,容易有做額外的事情,如檢查他們是否在界限內等

感謝您的任何幫助!是的,我也確信我的代碼看起來很可怕,但是我在完成工作之後會清理它們(他們不擅長教我們的風格,只是功能......)

編輯:對不起,忘了確切發佈的錯誤,那就是:

Traceback (most recent call last): 
    File "filepath etc etc", line 67, in <module> 
    xmin, ymin = xmin_list[0], ymin_list[1] 
IndexError: list index out of range 
+2

你做了一些調試嗎?使用調試器並逐步完成代碼。檢查變量。那麼你應該找到這個缺陷...... – 2011-03-02 22:33:09

+0

如果你需要幫助,你至少應該發佈堆棧跟蹤和其他相關信息(例如具體錯誤來自哪一行)。 – 2011-03-02 22:35:51

+0

什麼是錯誤? – 2011-03-02 22:35:58

回答

0
xmin, ymin = xmin_list[0], ymin_list[1] # < error comes in this line 

的錯誤這裏是[1]。如果前面的if聲明條件是False,那麼ymin_list仍然是您設置它的空列表,並且索引1已超過結尾。

此外,在第二部分中,您不需要使用那樣的range(len())。嘗試:

xmin = xmin_list[0] 
ymin = ymin_list[0] 
vmin = f((xmin, ymin)) 
for x in xmin_list: 
    for y in ymin_list: 
     v = f((x, y)) 
     if v < vmin: 
      xmin = x 
      ymin = y 
      vmin = v 

...來想想看,你初始化xminymin

+0

好吧,我現在看到爲什麼錯誤出現,就像你說的那樣。感謝第二部分的幫助,我現在修改了它。我已經初始化了xmin和ymin,在錯誤出現的位置。我只是將它們設置爲我想要從列表中獲取的值。編輯:哦,非常感謝你,我現在有工作。這也沒有幫助,因爲我在迭代循環之外發現了錯誤 – Scorpii 2011-03-03 00:32:06