Let’s take a look at my anonymously personalized function, f(x)=2x^3 + \cos(x).
We first produce a few graphs to visualize the behavior of the function. At most viewing scales, the cubic component of the function dominates, as seen here:
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import minimize
def f(x): return 2*x**3 + np.cos(x)
x = np.linspace(-5,5,5000)
y=f(x)
plt.plot(x,y)
plt.show()
If, however, we look at the portion very close to zero, we can see an interval in which the Cosine term dominates. We’ve got no hope of finding a minimum or maximum where the cubic function is the more significant, but it looks like there’s a local minima somewhere between 0 and 1.
x2 = np.linspace(-0.05,0.2,5000)
plt.plot(x2,f(x2))
plt.show()
We’ll start with the scipy.optimize.minimize function, for which we need to provide a starting value. It looks like there is a maximum at x=0, so we pick a starting point a little to the right to avoid issues involving f'(x)=0. Let’s try x=0.1.
minimize(lambda x: f(x), 0.1)
# fun: 0.9954021971219735
#hess_inv: array([[ 0.99123218]])
# jac: array([ -8.19563866e-08])
#message: 'Optimization terminated successfully.'
#nfev: 21
#nit: 5
#njev: 7
#status: 0
#success: True
#x: array([ 0.16590308])
We now plot this point along with the function, in a window where we can see the cosine-dominant shape.
plt.plot(x2,f(x2))
plt.plot(0.16590308,f(0.16590308),'ok')
plt.show()
We now wish to repeat the same task, but with the gss function instead.
gr = (np.sqrt(5) + 1) / 2
def gss(f, a, b, tol=10**(-10)):
c = b - (b - a) / gr
d = a + (b - a) / gr
while abs(c - d) > tol:
if f(c) < f(d):
b = d
else:
a = c
c = b - (b - a) / gr
d = a + (b - a) / gr
return (b + a) / 2
xmin = gss(f,0,2)
ymin = f(xmin)
print((xmin,ymin))
xg = np.linspace(-0.25,0.4,5000)
plt.plot(xg,f(xg))
plt.plot(xmin,ymin,'ok')
plt.show()
#(0.16590316905821892, 0.99540219712196987)
Success! Here’s the plot:
Above this x value, f(x) is monotonically increasing. At values of x<0, f(x) is also increasing, and so there is no global minima to be found, nor any additional local minima outside of the studied interval.