Optimization Exercise 1

Imports


In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt

Hat potential

The following potential is often used in Physics and other fields to describe symmetry breaking and is often known as the "hat potential":

$$ V(x) = -a x^2 + b x^4 $$

Write a function hat(x,a,b) that returns the value of this function:


In [2]:
# YOUR CODE HERE
#raise NotImplementedError()
def hat(x, a, b):
    return -a*x**2+b*x**4

In [3]:
assert hat(0.0, 1.0, 1.0)==0.0
assert hat(0.0, 1.0, 1.0)==0.0
assert hat(1.0, 10.0, 1.0)==-9.0

Plot this function over the range $x\in\left[-3,3\right]$ with $b=1.0$ and $a=5.0$:


In [4]:
a = 5.0
b = 1.0

In [10]:
# YOUR CODE HERE
#raise NotImplementedError()
x = np.linspace(-3,3,40)
plt.plot(x, hat(x,a,b))
plt.box(False)
plt.title('Hat Potential')
plt.xlabel('$x$')
plt.ylabel('$V(x)$');



In [11]:
assert True # leave this to grade the plot

Write code that finds the two local minima of this function for $b=1.0$ and $a=5.0$.

  • Use scipy.optimize.minimize to find the minima. You will have to think carefully about how to get this function to find both minima.
  • Print the x values of the minima.
  • Plot the function as a blue line.
  • On the same axes, show the minima as red circles.
  • Customize your visualization to make it beatiful and effective.

In [12]:
# YOUR CODE HERE
#raise NotImplementedError()
min1 = opt.minimize(hat, (-1.5), args=(a,b), bounds = [(-3,0)])
min2 = opt.minimize(hat, (1.5), args=(a,b), bounds = [(0,3)])
print ('The local minima are %f and %f' %(min1['x'][0], min2['x'][0]))  
plt.plot(x, hat(x,a,b), label='Hat Potential')
plt.scatter(min1['x'][0], hat(min1['x'][0],a,b), color = 'r',label = 'local min 1')
plt.scatter(min2['x'][0], hat(min2['x'],a,b), color = 'r',label = 'local min 2')
plt.box(False)
plt.tick_params(axis = 'x', top = 'off')
plt.tick_params(axis = 'y', right = 'off')
plt.title('Hat Potential')
plt.legend();


The local minima are -1.581139 and 1.581139

In [8]:
assert True # leave this for grading the plot

To check your numerical results, find the locations of the minima analytically. Show and describe the steps in your derivation using LaTeX equations. Evaluate the location of the minima using the above parameters.

Our equation is: \begin{equation*} V(x) = -5x^2+x^4 \end{equation*}

To solve for maxima and minima values you must take the derivative of your function.

\begin{equation*} \frac{dV}{dx} = -10x+4x^3 \end{equation*}

Set this derivative equal to zero and solve for x.

\begin{equation*}\\ 0 = x(-10+4x^2)\\ x = 0\\ x = \pm \sqrt{\frac{10}{4}}\\ \end{equation*}

x = 0 by the graph is a local maxima.

$$\pm \sqrt{\frac{10}{4}} = \pm 1.5811388$$

These are our minima!!