### Exercises of Optimization


```python
# import Python libraries
import numpy as np
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import sympy as sym
from sympy.plotting import plot
import pandas as pd
from IPython.display import display
from IPython.core.display import Math
```

**1.) Find the extrema in the function $f(x)=x^3−7.5x^2+18x−10$ analytically and determine if they are minimum or maximum.**



```python
x = sym.symbols('x')
f_de_x = (x**3) - 7.5 * (x**2) + 18*x - 10
Fdiff = sym.expand(sym.diff(f_de_x, x))
roots = sym.solve(Fdiff, x)
display(Math(sym.latex('Roots:') + sym.latex(roots)))
```


$$Roots:\left [ 2.0, \quad 3.0\right ]$$



```python
f = np.array([1,0])
f[0] = (roots[0]**3) - 7.5 * (roots[0]**2) + 18*roots[0] - 10
f[1] = (roots[1]**3) - 7.5 * (roots[1]**2) + 18*roots[1] - 10

print("For the  first root, f_de_x is", f[0])
print("For the second root, f_de_x is", f[1])
```

    For the  first root, f_de_x is 4
    For the second root, f_de_x is 3



```python
print("So, the maximun of f_de_x is ", np.max(f))
print("and the minimun of f_de_x is ", np.min(f))
```

    So, the maximun of f_de_x is  4
    and the minimun of f_de_x is  3


**2.) Find the minimum in the $f(x)=x^3−7.5x^2+18x−10$ using the gradient descent algorithm.**


```python
# From https://en.wikipedia.org/wiki/Gradient_descent
# The local minimum of $f(x)=x^4-3x^3+2$ is at x=9/4

cur_x = 6               # The algorithm starts at x=6
gamma = 0.01            # step size multiplier
precision = 0.00001
step_size = 1           # initial step size
max_iters = 10000       # maximum number of iterations
iters = 0               # iteration counter

f  = lambda x: (x**3) - 7.5 * (x**2) + 18*x - 10  # lambda function for f(x)
df = lambda x: 3*x**2 - 15*x + 18    # lambda function for the gradient of f(x)

while (step_size > precision) & (iters < max_iters):
    prev_x = cur_x
    cur_x -= gamma*df(prev_x)
    step_size = abs(cur_x - prev_x)
    iters+=1

print('True local minimum at {} with function value {}.'.format(9/4, f(9/4)))
print('Local minimum by gradient descent at {} with function value {}.'.format(cur_x, f(cur_x)))
```

    True local minimum at 2.25 with function value 3.921875.
    Local minimum by gradient descent at 3.000323195755751 with function value 3.5000001567170003.


d268d67c94bf1b442d4c31353fb536cacb75a458
ipynb
Jupyter Notebook
courses/modsim2018/tasks/Task_ForLecture19.ipynb
raissabthibes/bmc
840800fb94ea3bf188847d0771ca7197dfec68e3
MIT
courses/modsim2018/tasks/Task_ForLecture19.ipynb
raissabthibes/bmc
840800fb94ea3bf188847d0771ca7197dfec68e3
MIT
courses/modsim2018/tasks/Task_ForLecture19.ipynb
raissabthibes/bmc
840800fb94ea3bf188847d0771ca7197dfec68e3
MIT
Qwen/Qwen-72B
1. YES
2. YES