# GAMS Support Wiki

### Site Tools

gams:model_piecewise_linear_functions

This is an old revision of the document!

# How do I model piecewise linear functions?

How do I model a piecewise linear function in GAMS. The following fragment is not accepted:

`     Y =E=  (a*X+b)\$(X lt 0) + (c*X+d)\$(X ge 0 and X lt 1) +  (e*X+f)\$(X ge 1);`

With “if-then-else”'s within the equations you make the model non-linear. Even non-linear in a nasty sense: it can become discontinuous. In your specific case it would make it non-differentiable. The resulting model can not be solved using a general LP or even NLP solver (NLP solvers like MINOS and CONOPT like smooth continuous-differentiable functions).

In fact the piecewise linear function you describe can be modeled with some MIP solvers using socalled SOS 2 variables, or with general binary variables. Check textbooks like Nemhauser and Wolsey, Integer and Combinatorial Optimization (page 10) and H.P. Williams, Model Building in Mathematical Programming (section 7.3,9.3) for more information. Some examples are collected here.

Sometimes the following trick can be used: if you are minimizing Q one can introduce the inequalities: q >= aP+b q >= cP+d q >= eP+f because of the form of the P-Q curve. [here a picture approximately like:

```                  |
|
\
\
-----```

with two kinks]. (Note that the other way around does not work: q ⇐ aP+b, y ⇐ cP+b, y ⇐ eP+f would describe another feasible region!).

In most cases the best way would be to find a smooth approximation for this function. One could fit for instance a polynomial or an exponential. If needed you could construct a GAMS model for the least squares fit!