我對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
你做了一些調試嗎?使用調試器並逐步完成代碼。檢查變量。那麼你應該找到這個缺陷...... – 2011-03-02 22:33:09
如果你需要幫助,你至少應該發佈堆棧跟蹤和其他相關信息(例如具體錯誤來自哪一行)。 – 2011-03-02 22:35:51
什麼是錯誤? – 2011-03-02 22:35:58