Optimization Exercise 1

Imports


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

Hat potential


In [41]:
def hat(x,a,b):
    return b*x**4-a*x**2

In [42]:
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 [43]:
a = 5.0
b = 1.0
x = np.linspace(-3,3,60)

In [44]:
plt.plot(x,hat(x,a,b))


Out[44]:
[<matplotlib.lines.Line2D at 0x7f85fe1a8940>]

In [45]:
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 [54]:
min_1=opt.minimize(hat,1.5,args=(a,b))
minsx=[-1.58113881,1.58113881]
minsy=[-6.24999999,-6.24999999]
plt.figure(figsize=(10,5))
plt.plot(x,hat(x,a,b))
plt.scatter(minsx,minsy,100,c='r',marker='o')
plt.tight_layout()
plt.title('Hat Potential With Local Minimums')
plt.xlabel('x')
plt.ylabel('Hat Potential')
plt.grid()



In [ ]:
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 local minima will be when the derivatives of our function is equal to 0, and when the second derivative is postive.

The derivative is $4bx^{3}-2ax$, and if $a=5.0$ and $b=1.0$ then this will equal 0 when x is -1.5811, 0 and 1.5811. From looking at the graph is should be clear that when x is 0, it is a local maximum, whereas the other two are local minimms. These are nearly the exact same values as were calculate using scipy.


In [ ]: