### Sage code for 4(e) on challenge set 1.
### This command defines the class of polynomials in 2 variables, x and y, with real coefficients. It has to come before everything else we do here:
R. = RR['x,y']
### Define the function h(x, y):
h = (x + 0.25)*(y + 0.25) * exp(-x^2 - y^2)
### Pick a random starting point [m, n] in the region [-1, 1]x[-1, 1] (random() gives a number between 1 and 0, so we scale and shift its output.)
[m, n] = [random()*2 - 1, random()*2 - 1]
### Print the coordinates of the starting point together with the z-value h(m, n) at the starting point. Also print the gradient of h at [m, n].
print "start"
print [m, n, h(x = m, y = n)]
print h.gradient()(x = m, y = n)
### This is just a line break:
print "\n"
### Now take 10 steps with step size 0.2. (Note that the loop stops just before the end of the range, so i runs from 1 to 10 inclusive.)
for i in range(1, 11):
### take the i-th step in the direction of the gradient at the current point, updating [m, n] to the (x, y)-coordinates of the new point:
[m, n] = [m + h.diff(x)(x = m, y = n)*0.2, n + h.diff(y)(x = m, y = n)*0.2]
### print out the step number, (x, y, z)-coordinates of the new point, and the gradient at the new point:
print i
print [m, n, h(x = m, y = n)]
print h.gradient()(x = m, y = n)
print "\n"
### Print out the (x, y, z)-coordinates of the stopping point (this will repeat the last item of the loop).
print "end"
print [m, n, h(x = m, y = n)]
print h.gradient()(x = m, y = n)