Slack Variable Tutorial

Slack variables are additional variables used in optimization that convert an inequality constraint into an equality constraint, allowing the problem to be solved with standard methods, such as Interior Point Methods. Slack variables are typically denoted by the letter s and the value is always positive. Slack variables convert a constraint of the form "greater than or equal to" into an equation. For example, if the constraint is

$$2x + y \ge 4$$

then the constraint can be rewritten as

$$2x + y - 4 \ge 0$$

or with the slack variable (s)

$$s = 2x + y - 4$$

$$s\ge0$$

Slack variables are defined to transform an inequality expression into an equality expression with the added slack variable. The slack variable is defined by setting a lower bound of zero (≥0).

Inequality Constraint Form

x > b

Equality Constraint Form with Slack Variable

x = b + slack
slack ≥ 0



Example Problem

$$\begin{align}\min \quad & cost_{total}\\\mathrm{subject\;to} \quad & supply<b\\& cost_{total}=(supply-2)^2\end{align}$$

Gekko (Python) Solution

# Solve slack variable problem
#  Minimize   total_cost
#  Subject to supply < b
from gekko import GEKKO

b = 5
m = GEKKO(remote=False)
supply = m.Var()
total_cost = m.Var()

m.Equation(supply<b)
m.Equation(total_cost==(supply-2)**2)
m.Minimize(total_cost)

m.solve()

print(supply.value[0])
print(total_cost.value[0])

APMonitor Solution


Inequality Constraints

In Gekko Optimization Suite and the APMonitor Modeling Language, inequality constraints are automatically translated into equality constraints with slack variables. In APMonitor, slack variables can also be defined by starting a variable name with slk. When the model is parsed at run-time, any variable beginning with slk is automatically assigned a lower value of zero. Alternatively, inequality constraints are automatically converted to equality constraints with a slack variable.

💬