I’m relatively new to python, have done it a bit for my physics university course.
At the moment I’m trying to write a program to calculate some stuff to do with vector functions, that’s not really important though as I have it all working up until the last section.
The program up to this point produces a load of local minima on a 2D graph, however I need to find the minimum value overall.
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
I’ve included the rest of the big for loop below for completeness, but it’s not the bit giving me an error (yet).
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]
So it’s clearly something around the middle of the whole loop, but I’m not sure why I’m getting the error. I’m trying to access the last elements of each list, then append them to the list (after checking for fitting the conditions x0, x1 etc).
I’m not sure why it’s not working..
I’m also sure this is a fairly complex way of going about finding the minimum, but it seemed logical to me, and I get confused easily having to do extra things like check they’re within the boundaries etc.
Thanks for any help! And yes I’m also sure my coding looks horrible and messy, but I’ll tidy it up after I get it working (they’re not very good at teaching us style, only function..)
EDIT: Sorry, forgot to post the error exactly, here it is:
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
The error here is the
[1]. If the precedingifstatement conditions areFalse, thenymin_listis still the empty list you set it to, and index 1 is past the end.Also, in the second part you don’t need to be using
range(len())like that. Try:… Come to think of it, are you initializing
xminandymin?