119 KiB
119 KiB
In [1]:
%matplotlib inline
import numpy as np
import numpy.linalg as la
import scipy.optimize as sopt
import matplotlib.pyplot as pt
from mpl_toolkits.mplot3d import axes3d
def f(x):
return 0.5*x[0]**2 + 2.5*x[1]**2
def df(x):
return np.array([x[0], 5*x[1]])
fig = pt.figure()
ax = fig.gca(projection="3d")
xmesh, ymesh = np.mgrid[-2:2:50j,-2:2:50j]
fmesh = f(np.array([xmesh, ymesh]))
ax.plot_surface(xmesh, ymesh, fmesh)[0;31m---------------------------------------------------------------------------[0m [0;31mTypeError[0m Traceback (most recent call last) Cell [0;32mIn[1], line 18[0m [1;32m 15[0m [38;5;28;01mreturn[39;00m np[38;5;241m.[39marray([x[[38;5;241m0[39m], [38;5;241m5[39m[38;5;241m*[39mx[[38;5;241m1[39m]]) [1;32m 17[0m fig [38;5;241m=[39m pt[38;5;241m.[39mfigure() [0;32m---> 18[0m ax [38;5;241m=[39m [43mfig[49m[38;5;241;43m.[39;49m[43mgca[49m[43m([49m[43mprojection[49m[38;5;241;43m=[39;49m[38;5;124;43m"[39;49m[38;5;124;43m3d[39;49m[38;5;124;43m"[39;49m[43m)[49m [1;32m 20[0m xmesh, ymesh [38;5;241m=[39m np[38;5;241m.[39mmgrid[[38;5;241m-[39m[38;5;241m2[39m:[38;5;241m2[39m:[38;5;241m50[39mj,[38;5;241m-[39m[38;5;241m2[39m:[38;5;241m2[39m:[38;5;241m50[39mj] [1;32m 21[0m fmesh [38;5;241m=[39m f(np[38;5;241m.[39marray([xmesh, ymesh])) [0;31mTypeError[0m: gca() got an unexpected keyword argument 'projection'
<Figure size 640x480 with 0 Axes>
In [2]:
pt.axis("equal")
pt.contour(xmesh, ymesh, fmesh)
guesses = [np.array([2, 2./5])]In [3]:
x = guesses[-1]
s = -df(x)In [4]:
def f1d(alpha):
return f(x + alpha*s)
alpha_opt = sopt.golden(f1d)
next_guess = x + alpha_opt * s
guesses.append(next_guess)
print(next_guess)In [5]:
pt.axis("equal")
pt.contour(xmesh, ymesh, fmesh, 50)
it_array = np.array(guesses)
pt.plot(it_array.T[0], it_array.T[1], "x-")Warning:
Output truncated. This notebook contains too many cells to display efficiently.