Minima and roots of a function

adapted from http://www.scipy-lectures.org/ by Marco Della Vedova - marco.dellavedova@unicatt.it

Last update: June 2018

Problem statement

Given the function

$f(x) = x^2 + 10 \sin(x)$

draw it in the interval [-10, 10], find its local minima and roots.

Proposed solution

Function definition

In [1]:
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)

Finding minima

In [2]:
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)
Global minima found [-1.30641113]
Local minimum found 3.8374671195

Finding roots

In [3]:
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)
First root found [ 0.]
Second root found [-2.47948183]

Plotting

In [4]:
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()