adapted from http://www.scipy-lectures.org/ by Marco Della Vedova - marco.dellavedova@unicatt.it
Last update: June 2018
Given the function
$f(x) = x^2 + 10 \sin(x)$
draw it in the interval [-10, 10], find its local minima and roots.
import numpy as np
f = lambda x: x**2 + 10*np.sin(x)
interval = [-10, 10]
# or, alternatively:
# def f(x):
# return x**2 + 10*np.sin(x)
from scipy import optimize
# Global optimization
grid = (interval[0], interval[1], 0.1)
xmin_global = optimize.brute(f, (grid, ))
print("Global minima found %s" % xmin_global)
# Constrain optimization
xmin_local = optimize.fminbound(f, 0, 10)
print("Local minimum found %s" % xmin_local)
root = optimize.root(f, 1) # our initial guess is 1
print("First root found %s" % root.x)
root2 = optimize.root(f, -2.5)
print("Second root found %s" % root2.x)
import matplotlib.pyplot as plt
x = np.arange(interval[0], interval[1], 0.1)
# Plot the function
plt.plot(x, f(x), 'b-', label="f(x)")
# Plot the minima
xmins = np.array([xmin_global[0], xmin_local])
plt.plot(xmins, f(xmins), 'go', label="Minima")
# Plot the roots
roots = np.array([root.x, root2.x])
plt.plot(roots, f(roots), 'kv', label="Roots")
# Decorate the figure
plt.legend(loc='best')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.axhline(0, color='gray')
plt.show()