## Using different equations based on the value of a function

**Moderator:** aileen

**Forum rules**

Please ask questions in the other sub-forums

### Using different equations based on the value of a function

How to arrive at a system in which another equation is enforced based on the value of a function?

### Re: Using different equations based on the value of a function

To be fairly general, use the following statement:

Note that the distinction between

Start by writing, in GAMS,

So, when

Now declare a binary variable,

Next, split the two terms of

So,

Finally split just the

So,

Taken together, the last two sections give

Code: Select all

```
z = f(x) when y > 0
z = g(x) when y < 0
```

*>=*and just*>*is not meaningful for a numerical algorithm on a finite precision machine.Start by writing, in GAMS,

Code: Select all

```
Variable fs, gs;
z =E= (f(x) - fs) + (g(x) - gs);
```

*y > 0*, we want*fs = 0*and*gs = g(x)*. When*y < 0*, we want*fs = f(x)*and*gs = 0*;Now declare a binary variable,

*b*, that will be 1 when*y > 0*and 0 and*y < 0*.Code: Select all

```
Binary Variable b;
Positive Variable yp, yn;
y =E= yp - yn;
yp =L= ymax * b;
yn =L= ymax * (1 - b);
```

*z*into positive and negative parts.Code: Select all

```
Positive Variable fp, fn, gp, gn;
f(x) - fs =E= fp - fn;
g(x) - gs =E= gp - gn;
fp + fn =L= fmax * b;
gp + gn =L= gmax * (1 - b);
```

*b = 0*⇒*fs = f(x)*and*b = 1*⇒*gs = g(x)*.Finally split just the

*f*and*g*slacks*fs*and*gs*into positive and negative components.Code: Select all

```
Positive Variable fsp, fsn, gsp, gsn;
fs =E= fsp - fsn;
gs =E= gsp - gsn;
fsp + fsn =L= fmax* (1 - b);
gsp + gsn =L= gmax * b;
```

*b = 0*⇒*gs = 0*and*b = 1*⇒*fs = 0*.Taken together, the last two sections give

*b = 0*⇒*z = g(x)*and*b = 1*⇒*z = f(x)*.