# Simple nonlinear complementarity problem

**Randall Romero Aguilar, PhD**

This demo is based on the original Matlab demo accompanying the  <a href="https://mitpress.mit.edu/books/applied-computational-economics-and-finance">Computational Economics and Finance</a> 2001 textbook by Mario Miranda and Paul Fackler.

Original (Matlab) CompEcon file: **demslv13.m**

Running this file requires the Python version of CompEcon. This can be installed with pip by running

    !pip install compecon --upgrade

<i>Last updated: 2021-Oct-01</i>
<hr>

## About

The problem is to solve

\begin{equation}
f(x, y) = \begin{bmatrix}1+xy -2x^3-x\\ 2x^2-y\end{bmatrix}
\end{equation}

subject to $0 \leq x, y \leq 1$


```python
from compecon import MCP, jacobian
import numpy as np

x0 = [0.5, 0.5]    
```

### Solving the problem without the Jacobian
To solve this problem we create a **MCP** object using a lambda function.


```python
def func(z):
    x, y = z
    return np.array([1 + x*y - 2*x**3 - x, 2*x**2 - y])
                      
F = MCP(func, [0, 0], [1,1])
```

Solve for initial guess $x_0 = [0.5, 0.5]$


```python
x = F.zero(x0, transform='minmax', show=True)
#x = F.zero(x0, transform='ssmooth', show=True) # FIXME: generates error
print(f'Solution is {x=}.')
```

    Using the MINMAX transformation
    Solving nonlinear equations by Broyden's method
    it    bstep  change
    --------------------
       0     1  1.56e-01
       1     1  1.14e-01
       2     1  1.01e-01
       3     0  3.66e-02
       4     0  1.33e-03
       5     0  1.86e-05
       6     0  2.02e-07
       7     0  1.13e-09
    Solution is x=array([0.7937, 1.    ]).


### Solving the problem with the Jacobian


```python
def func2(z):
    x, y = z
    f = [1 + x*y - 2*x**3 - x, 2*x**2 - y]
    J = [[y-6*x**2-1, x],[4*x, -1]]
    return np.array(f), np.array(J)                  

F2 = MCP(func2, [0, 0], [1,1])
```


```python
x = F2.zero(x0, transform='minmax', show=True)
print(f'Solution is {x=}.')
```

    Using the MINMAX transformation
    Solving nonlinear equations by Newton's method
    it    bstep  change
    --------------------
       0     1  1.56e-01
       1     0  9.84e-03
       2     0  3.19e-05
       3     0  3.40e-10
    Solution is x=array([0.7937, 1.    ]).


ipynb
836a75a2ccbb5cdbbd97edd6ace847c9243ae260
Jupyter Notebook
2020-05-15T09:49:16.000Z
2017-02-25T08:10:38.000Z
c7a75f57f8472c972fddcace8ff7b86fee049d29
MIT
randall-romero/CompEcon-python
_build/jupyter_execute/notebooks/slv/13 Simple nonlinear complementarity problem.ipynb
c7a75f57f8472c972fddcace8ff7b86fee049d29
2018-03-31T01:36:46.000Z
2017-09-10T04:48:54.000Z
MIT
randall-romero/CompEcon
_build/jupyter_execute/notebooks/slv/13 Simple nonlinear complementarity problem.ipynb
c7a75f57f8472c972fddcace8ff7b86fee049d29
MIT
randall-romero/CompEcon-python
_build/jupyter_execute/notebooks/slv/13 Simple nonlinear complementarity problem.ipynb
2020-08-23T21:04:34.000Z
2016-12-14T13:21:27.000Z