### DEMSLV02

# Compute root of Rosencrantz function

Compute root of 

\begin{equation}
f(x_1,x_2)= \begin{bmatrix}200x_1(x_2-x_1^2) + 1-x_1 \\ 100(x_1^2-x_2)\end{bmatrix}
\end{equation}

using Newton and Broyden methods. Initial values generated randomly.  True root is $x_1=1, \quad x_2=1$.


```python
from demos.setup import np, tic, toc
from compecon import NLP
```

### Set up the problem


```python
def f(x):
    x1, x2 = x
    fval = [200 * x1 * (x2 - x1 ** 2) + 1 - x1, 100 * (x1 ** 2 - x2)]
    fjac = [[200 * (x2 - x1 ** 2) - 400 * x1 ** 2 - 1, 200 * x1],
            [200 * x1, -100]]
    return np.array(fval), np.array(fjac)

problem = NLP(f)
```

### Randomly generate starting point


```python
problem.x0 = np.random.randn(2)
```

### Compute root using Newton method


```python
t0 = tic()
x1 = problem.newton()
t1 = 100 * toc(t0)
n1 = problem.fnorm
```

### Compute root using Broyden method


```python
t0 = tic()
x2 = problem.broyden()
t2 = 100 * toc(t0)
n2 = problem.fnorm
```

### Print results


```python
print('Hundreds of seconds required to compute root of Rosencrantz function')
print('f(x1,x2)= [200*x1*(x2-x1^2)+1-x1;100*(x1^2-x2)] via Newton and Broyden')
print('methods, starting at x1 = {:4.2f} x2 = {:4.2f}'.format(*problem.x0))
print('\nMethod      Time   Norm of f        x1     x2\n', '-' * 45)
print('Newton  %8.2f    %8.0e     %5.2f  %5.2f' % (t1, n1, x1[0], x1[1]))
print('Broyden %8.2f    %8.0e     %5.2f  %5.2f' % (t2, n2, x2[0], x2[1]))
```

    Hundreds of seconds required to compute root of Rosencrantz function
    f(x1,x2)= [200*x1*(x2-x1^2)+1-x1;100*(x1^2-x2)] via Newton and Broyden
    methods, starting at x1 = 1.22 x2 = 1.28
    
    Method      Time   Norm of f        x1     x2
     ---------------------------------------------
    Newton      1.60       5e-13      1.00   1.00
    Broyden     1.60       6e-09      1.00   1.00


3441ccc6b06be2f3bcad8dc691fdebac2609b634
ipynb
Jupyter Notebook
notebooks/slv/02 Compute root of Rosencrantz function.ipynb
daniel-schaefer/CompEcon-python
d3f66e04a7e02be648fc5a68065806ec7cc6ffd6
MIT
notebooks/slv/02 Compute root of Rosencrantz function.ipynb
daniel-schaefer/CompEcon-python
d3f66e04a7e02be648fc5a68065806ec7cc6ffd6
MIT
notebooks/slv/02 Compute root of Rosencrantz function.ipynb
daniel-schaefer/CompEcon-python
d3f66e04a7e02be648fc5a68065806ec7cc6ffd6
MIT
2021-06-01T03:47:35.000Z
2021-06-01T03:47:35.000Z
Qwen/Qwen-72B
1. YES
2. YES