628 KiB
628 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 x[0]**2 + 3.0*x[1]**2
def df(x):
return np.array([2*x[0], 6*x[1]])
fig = pt.figure()
ax = fig.gca(projection="3d")
xmesh, ymesh = np.mgrid[-3:3:50j,-3:3:50j]
fmesh = f(np.array([xmesh, ymesh]))
ax.plot_surface(xmesh, ymesh, fmesh)Out [1]:
/var/folders/td/3yk470mj5p931p9dtkk0y6jw0000gn/T/ipykernel_8843/3838917029.py:18: MatplotlibDeprecationWarning: Calling gca() with keyword arguments was deprecated in Matplotlib 3.4. Starting two minor releases later, gca() will take no keyword arguments. The gca() function should only be used to get the current axes, or if no axes exist, create new axes with default keyword arguments. To create a new axes with non-default arguments, use plt.axes() or plt.subplot(). ax = fig.gca(projection="3d")
<mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x1194ee790>
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)[ 0.69230769 -0.38461539]
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-")Out [5]:
[<matplotlib.lines.Line2D at 0x128f6eee0>]
Warning:
Output truncated. This notebook contains too many cells to display efficiently.