Integer and float expressions

Describes the use of constants, data, decision variables, and operators within OPL expressions.

Integer expressions

Integer expressions are constructed from integer constants, integer data, integer decision variables, and the traditional integer operators such as +, -, *, div, mod (or %). The operator div represents the integer division (for example, 8 div 3 == 2) and the operator mod or % represents the integer remainder. OPL also supports the function abs, which returns the absolute value of its argument, and the built-in constant maxint, which represents the largest integer representable in OPL.

Note that expressions involving large integers may produce an overflow. In the following example for int, an overflow is detected.

int a=maxint+2;
float b=infinity+2;

execute
{
   writeln(a);
   writeln(b);
}

The Problems tab in the IDE displays the error messages.

Screen capture of overflow errors in IDE

Most int expressions (such as % or div) are not available for constraints defined in CPLEX models, but are available for CP models. See also Constraints available in constraint programming.

Float expressions

Float expressions are constructed from floats, float data and variables, as well as operators such as +, -, /, *. In addition, OPL contains a float constant infinity to represent ∞ and a variety of float functions, depicted in OPL functions in the Language Quick Reference.

Conditional expressions

Conditional expressions are expressed like this:


(condition)?thenExpr : elseExpr

where condition is a ground condition with no decision variable. If condition is true, the condition evaluates to thenExpr ; otherwise, it evaluates to elseExpr.

Examples

int value = ...; 
int signValue = (value>0) ? 1 : (value<0) ? -1 : 0;
int absValue = (value>=0) ? value : -value;

See the numeric functions in Summary table of OPL functions in the Language Quick Reference.

Counting expressions

Among integer expressions, there are also some combinatorial expressions. For example, you can use the count function to count the number of times a particular value appears in an array of decision variables. You can use such an expression in modeling constraints only if the modeling constraints are part of a model that is solved by the CP Optimizer engine (that is, starting with the using CP; statement).

The constraint


count(x, 2) == 3;

states that in the array of variables x, exactly three variables take the value 2.

For more information, see count in the Language Quick Reference.