# GAMS Support Wiki

### Site Tools

gams:use_different_equations_based_on_the_value_of_a_function

# Differences

This shows you the differences between two versions of the page.

 — gams:use_different_equations_based_on_the_value_of_a_function [2007/08/10 10:56] (current) Line 1: Line 1: + ====== Using different equations based on the value of a function ====== + The question is how to have to regimes where a different equation is enforced based on the value of some function. To be fairly general, use the following statement: + <​code>​ + z = f(x) when y > 0 + z = g(x) when y < 0 + ​ + Note that the distinction between ''>​=''​ and just ''>''​ is not meaningful for a numerical algorithm on a finite precision machine. + + Start by writing, in GAMS, + <​code>​ + ​Variable fs, gs; + z =E= (f(x) - fs) + (g(x) - gs); + ​ + So, when ''​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>​ + ​Binary Variable b; + ​Positive Variable yp, yn; + y =E= yp - yn; + + yp =L= ymax * b; + yn =L= ymax * (1 - b); + ​ + Next, spit the two terms of ''​z''​ into positive and negative parts. + <​code>​ + ​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); + ​ + So, ''​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>​ + ​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; + ​ + So, ''​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)''​. 