# Exercises 2 - Answers

## Exercise 1

The profit that you make for each kwH is $2-0.01x^2-(1-0.01x)$. Thus, the amount of profit that you make is
$$
(1+0.01x-0.01x^2)x=x+0.01x^2-0.01x^3.
$$
Thus, the optimization problem is
$$
\begin{align}
\max \qquad & x+0.01x^2-0.01x^3\\
\text{s.t.} \qquad & 0\leq x \leq 50.
\end{align}
$$

## Exercise 2


```python
def bisection_line_search(a,b,f,L,epsilon):
    x = a
    y = b
    while y-x>2*L:
        if f((x+y)/2+epsilon)>f((x+y)/2-epsilon):
            y=(x+y)/2+epsilon
        else:
            x = (x+y)/2-epsilon
    return (x+y)/2
```


```python
def f_ex2(x):
    return (1-x)**2+x
```


```python
print f_ex2(0.5), f_ex2(0), f_ex2(1)
```

    0.75 1 1



```python
bisection_line_search(0,2,f_ex2,0.0001,1e-6)
```




    0.49993946490478514



## Exercise 3


```python
import math
def golden_section_line_search(a,b,f,L):
    x = a
    y = b
    f_left = f(y-(math.sqrt(5.0)-1)/2.0*(y-x)) #funtion eval 
    f_right = f(x+(math.sqrt(5.0)-1)/2.0*(y-x)) #function eval
    while y-x>2*L:
        if f_left > f_right:
            x = y-(math.sqrt(5.0)-1)/2.0*(y-x)
            f_left = f_right #no function eval
            f_right = f(x+(math.sqrt(5.0)-1)/2.0*(y-x)) #function eval
        else:
            y = x+(math.sqrt(5.0)-1)/2.0*(y-x)
            f_right = f_left #no function eval
            f_left = f(y-(math.sqrt(5.0)-1)/2.0*(y-x)) #function eval
    return (x+y)/2
```


```python
golden_section_line_search(0,2,f_ex2,0.0001)
```




    0.4999795718254958



## Exercise 4

Now, $f(x) = (1-x)^2+x$. Thus, 
$$
f'(x)=2(1-x)(-1)+1= -1 +2x.
$$


If $f'(x) = 0$, then $2x=1$ and $x=\frac 12$.
This is a local minimum since,
$$
f''(x) = 2,
$$
which is greater than $0$.

This means that the algorithms work!

993c34c1396cc96d79ae87fc52a378260dff98c6
ipynb
Jupyter Notebook
Exercise 2 answers.ipynb
maeehart/TIES483
cce5c779aeb0ade5f959a2ed5cca982be5cf2316
CC-BY-3.0
2019-04-26T12:46:14.000Z
2021-11-23T03:38:59.000Z
Exercise 2 answers.ipynb
maeehart/TIES483
cce5c779aeb0ade5f959a2ed5cca982be5cf2316
CC-BY-3.0
Exercise 2 answers.ipynb
maeehart/TIES483
cce5c779aeb0ade5f959a2ed5cca982be5cf2316
CC-BY-3.0
2016-01-08T16:28:11.000Z
2021-04-10T05:18:10.000Z
Qwen/Qwen-72B
1. YES
2. YES