TExcelTAD
Home › Linear Programming & Duality for Algorithms › Complementary Slackness and Optimality Certificates

Complementary Slackness and Optimality Certificates

Strong duality says that optimal primal and dual values are equal. Complementary slackness says how they manage it: at an optimum, a dual variable can be non-zero only on a primal constraint that is tight, and a primal variable can be non-zero only where its dual constraint is tight. These conditions turn optimality into a system of equations you can solve by hand, they are the invariant of every primal-dual algorithm (the Hungarian method for assignment, the primal-dual approximation algorithms of the next course), and they give dual variables their economic meaning as prices. This lesson proves the theorem, uses it to certify a claimed optimum, and builds a small exact certificate checker in Python and C++.

The theorem

For the pair (P) max⁡{cTx:Ax≤b, x≥0}(P)\ \max \{ c^T x : Ax \le b,\ x \ge 0 \} and (D) min⁡{bTy:ATy≥c, y≥0}(D)\ \min \{ b^T y : A^T y \ge c,\ y \ge 0 \}:

Theorem (complementary slackness). Feasible xx and yy are both optimal if and only if

yi (bi−aiTx)=0  for every row iandxj ((ATy)j−cj)=0  for every column j.y_i \, (b_i - a_i^T x) = 0 \ \text{ for every row } i \qquad \text{and} \qquad x_j \, \big( (A^T y)_j - c_j \big) = 0 \ \text{ for every column } j .

Proof. Look at the chain of weak duality again:

cTx  ≤  (ATy)Tx  =  yTAx  ≤  yTb.c^T x \;\le\; (A^T y)^T x \;=\; y^T A x \;\le\; y^T b .

The first gap is ∑jxj((ATy)j−cj)\sum_j x_j ((A^T y)_j - c_j), a sum of non-negative terms; the second is ∑iyi(bi−aiTx)\sum_i y_i (b_i - a_i^T x), also a sum of non-negative terms. By weak and strong duality, xx and yy are both optimal exactly when cTx=bTyc^T x = b^T y, that is, when both gaps are zero, that is, when every single term is zero. □\square

In words: either a constraint is tight or its dual variable is zero, for both sides. The proof needs only weak duality for the "if" direction. For "only if" it needs strong duality, which guarantees that optimal xx and yy have equal values.

Using it to certify a claimed optimum

Someone claims that x∗=(0,0,2)x^* = (0, 0, 2) is optimal for max⁡x1+2x2+4x3\max x_1 + 2x_2 + 4x_3 subject to x1+x2+2x3≤4x_1 + x_2 + 2x_3 \le 4, 2x1+x3≤52x_1 + x_3 \le 5, 2x1+x2+3x3≤72x_1 + x_2 + 3x_3 \le 7, x≥0x \ge 0. Complementary slackness tells you what a matching dual must look like:

  • rows 2 and 3 have slack (2<52 < 5, 6<76 < 7), so y2=y3=0y_2 = y_3 = 0;
  • x3>0x_3 > 0, so the third dual constraint is tight: 2y1+y2+3y3=42y_1 + y_2 + 3y_3 = 4, hence y1=2y_1 = 2.

It remains to check that this y=(2,0,0)y = (2, 0, 0) is dual feasible: y≥0y \ge 0, and y1+2y2+2y3=2≥1y_1 + 2y_2 + 2y_3 = 2 \ge 1, y1+y3=2≥2y_1 + y_3 = 2 \ge 2. It is, so x∗x^* is optimal, with a proof anyone can verify. If the forced system had no non-negative solution, or the solution violated a dual constraint, x∗x^* would not be optimal.

In general the forced conditions form a linear feasibility problem (some yi=0y_i = 0, some dual constraints as equations, the rest as inequalities). The program solves it with SciPy for three candidate vertices.

python · try it yourself
from scipy.optimize import linprog

c = [1, 2, 4]
A = [[1, 1, 2], [2, 0, 1], [2, 1, 3]]
b = [4, 5, 7]

def certify(x):
    m, n = len(A), len(c)
    slack = [b[i] - sum(A[i][j] * x[j] for j in range(n)) for i in range(m)]
    bounds = [(0, 0) if slack[i] > 0 else (0, None) for i in range(m)]           # slack row -> y_i = 0
    eq = [j for j in range(n) if x[j] > 0]                                        # x_j > 0 -> tight dual row
    ineq = [j for j in range(n) if x[j] == 0]
    res = linprog([0] * m,
                  A_eq=[[A[i][j] for i in range(m)] for j in eq] or None, b_eq=[c[j] for j in eq] or None,
                  A_ub=[[-A[i][j] for i in range(m)] for j in ineq] or None, b_ub=[-c[j] for j in ineq] or None,
                  bounds=bounds, method="highs")
    value = sum(cj * xj for cj, xj in zip(c, x))
    if res.status == 0:
        return f"value {value}: optimal, certificate y = {[round(float(v), 6) for v in res.x]}"
    return f"value {value}: not optimal (no dual solution satisfies complementary slackness)"

for x in [(0, 0, 2), (2, 0, 1), (2.5, 1.5, 0)]:
    print(x, "->", certify(x))
(0, 0, 2) -> value 8: optimal, certificate y = [2.0, 0.0, 0.0]
(2, 0, 1) -> value 6: not optimal (no dual solution satisfies complementary slackness)
(2.5, 1.5, 0) -> value 5.5: not optimal (no dual solution satisfies complementary slackness)

An exact certificate checker

Given both xx and yy, no solver is needed at all: check primal feasibility, dual feasibility and the complementary slackness products, in exact arithmetic. This is the check to run on the output of any LP solver whose answer matters.

python · try it yourself
from fractions import Fraction as F

def check(c, A, b, x, y):
    m, n = len(A), len(c)
    x, y = [F(v) for v in x], [F(v) for v in y]
    Ax = [sum(A[i][j] * x[j] for j in range(n)) for i in range(m)]
    ATy = [sum(A[i][j] * y[i] for i in range(m)) for j in range(n)]
    report = {
        "primal feasible": all(v >= 0 for v in x) and all(Ax[i] <= b[i] for i in range(m)),
        "dual feasible": all(v >= 0 for v in y) and all(ATy[j] >= c[j] for j in range(n)),
        "rows: y_i * slack_i = 0": all(y[i] * (b[i] - Ax[i]) == 0 for i in range(m)),
        "columns: x_j * surplus_j = 0": all(x[j] * (ATy[j] - c[j]) == 0 for j in range(n)),
    }
    for k, v in report.items():
        print(f"  {k:30} {v}")
    print("  values:", sum(c[j] * x[j] for j in range(n)), "and", sum(b[i] * y[i] for i in range(m)))
    return all(report.values())

c, A, b = [3, 2], [[2, 1], [1, 3], [1, 0]], [10, 15, 4]
print("workshop, x = (3, 4), y = (7/5, 1/5, 0):")
print("  OPTIMAL" if check(c, A, b, [3, 4], [F(7, 5), F(1, 5), 0]) else "  not certified")
print("workshop, x = (4, 2), y = (2, 0, 1):")
print("  OPTIMAL" if check(c, A, b, [4, 2], [2, 0, 1]) else "  not certified")
workshop, x = (3, 4), y = (7/5, 1/5, 0):
  primal feasible                True
  dual feasible                  True
  rows: y_i * slack_i = 0        True
  columns: x_j * surplus_j = 0   True
  values: 17 and 17
  OPTIMAL
workshop, x = (4, 2), y = (2, 0, 1):
  primal feasible                True
  dual feasible                  True
  rows: y_i * slack_i = 0        True
  columns: x_j * surplus_j = 0   False
  values: 16 and 24
  not certified

In the second pair both points are feasible and every row product vanishes, but the column condition fails: x1=4>0x_1 = 4 > 0 while the first dual constraint has surplus 2y1+y2+y3−3=22y_1 + y_2 + y_3 - 3 = 2. The values 1616 and 2424 differ by exactly x1⋅2=8x_1 \cdot 2 = 8, the sum of the non-zero products. The checker reports which condition fails, which is the point of writing it.

In C++

The same checker with an exact rational type. It returns a verdict per condition, so it can serve as a test oracle for an LP solver.

cpp · try it yourself
#include <cstdio>
#include <numeric>
#include <vector>

struct Q {
    long long p, q;
    Q(long long a = 0, long long b = 1) : p(a), q(b) { if (q < 0) { p = -p; q = -q; } long long g = std::gcd(p < 0 ? -p : p, q); if (g > 1) { p /= g; q /= g; } }
    Q operator+(Q o) const { return Q(p * o.q + o.p * q, q * o.q); }
    Q operator-(Q o) const { return Q(p * o.q - o.p * q, q * o.q); }
    Q operator*(Q o) const { return Q(p * o.p, q * o.q); }
    bool operator<=(Q o) const { return p * o.q <= o.p * q; }
    bool zero() const { return p == 0; }
};
using Vec = std::vector<Q>;

bool check(const std::vector<Vec>& A, const Vec& b, const Vec& c, const Vec& x, const Vec& y) {
    size_t m = A.size(), n = c.size();
    bool pf = true, df = true, cs_rows = true, cs_cols = true;
    Q px, dy;
    for (size_t j = 0; j < n; j++) { pf = pf && Q(0) <= x[j]; px = px + c[j] * x[j]; }
    for (size_t i = 0; i < m; i++) { df = df && Q(0) <= y[i]; dy = dy + b[i] * y[i]; }
    for (size_t i = 0; i < m; i++) {
        Q ax;
        for (size_t j = 0; j < n; j++) ax = ax + A[i][j] * x[j];
        pf = pf && ax <= b[i];
        cs_rows = cs_rows && (y[i] * (b[i] - ax)).zero();
    }
    for (size_t j = 0; j < n; j++) {
        Q aty;
        for (size_t i = 0; i < m; i++) aty = aty + A[i][j] * y[i];
        df = df && c[j] <= aty;
        cs_cols = cs_cols && (x[j] * (aty - c[j])).zero();
    }
    std::printf("  primal %d, dual %d, row CS %d, column CS %d, values %lld/%lld and %lld/%lld\n",
                pf, df, cs_rows, cs_cols, px.p, px.q, dy.p, dy.q);
    return pf && df && cs_rows && cs_cols;
}

int main() {
    std::vector<Vec> A = {{Q(2), Q(1)}, {Q(1), Q(3)}, {Q(1), Q(0)}};
    Vec b = {Q(10), Q(15), Q(4)}, c = {Q(3), Q(2)};
    std::printf("x = (3, 4), y = (7/5, 1/5, 0):\n");
    std::printf("  %s\n", check(A, b, c, {Q(3), Q(4)}, {Q(7, 5), Q(1, 5), Q(0)}) ? "OPTIMAL" : "not certified");
    std::printf("x = (4, 2), y = (2, 0, 1):\n");
    std::printf("  %s\n", check(A, b, c, {Q(4), Q(2)}, {Q(2), Q(0), Q(1)}) ? "OPTIMAL" : "not certified");
}
x = (3, 4), y = (7/5, 1/5, 0):
  primal 1, dual 1, row CS 1, column CS 1, values 17/1 and 17/1
  OPTIMAL
x = (4, 2), y = (2, 0, 1):
  primal 1, dual 1, row CS 1, column CS 0, values 16/1 and 24/1
  not certified

Dual variables as prices

At an optimal pair, yiy_i measures how much the optimum would improve per unit of extra right-hand side bib_i, as long as the optimal basis stays the same: since z∗=bTy∗z^* = b^T y^* and y∗y^* does not depend on bb within that range, ∂z∗/∂bi=yi∗\partial z^* / \partial b_i = y_i^*. Complementary slackness is then common sense: a resource that is not used up (positive slack) has price zero. The program raises the capacity of the first row of the three-variable LP, whose price is y1=2y_1 = 2.

python · try it yourself
from scipy.optimize import linprog

c, A = [1, 2, 4], [[1, 1, 2], [2, 0, 1], [2, 1, 3]]
for b1 in [4, 5, 6, 7, 8, 9]:
    r = linprog([-v for v in c], A_ub=A, b_ub=[b1, 5, 7], bounds=[(0, None)] * 3, method="highs")
    print(f"b1 = {b1}: optimum {round(float(-r.fun), 6)}")
b1 = 4: optimum 8.0
b1 = 5: optimum 10.0
b1 = 6: optimum 12.0
b1 = 7: optimum 14.0
b1 = 8: optimum 14.0
b1 = 9: optimum 14.0

Each extra unit of b1b_1 is worth 2 up to b1=7b_1 = 7. There the optimum x=(0,7,0)x = (0, 7, 0) also makes row 3 tight, and beyond it row 3 is the binding constraint: more of resource 1 is worthless, its price drops to 0, and the optimal dual solution changes. Shadow prices are local information, valid on an interval of right-hand sides, which Sensitivity and Shadow Prices develops.

Note: Approximation algorithms use relaxed complementary slackness: require xj>0⇒cj≤(ATy)j≤αcjx_j > 0 \Rightarrow c_j \le (A^T y)_j \le \alpha c_j only up to a factor. The same weak-duality chain then shows that xx is within a factor α\alpha of optimal. The primal-dual method of Approximation Algorithms is built on this.

Test yourself

At an optimal pair, primal constraint ii has positive slack. What do you know?

  1. yi>0y_i > 0
  2. yi=0y_i = 0
  3. xi=0x_i = 0
  4. The LP is degenerate

Which part of the weak duality chain do the complementary slackness conditions make tight?

  1. Only the first inequality
  2. Both inequalities: each is a sum of non-negative products that must all vanish
  3. Neither
  4. Only the equality in the middle

What does the optimal dual value yi∗y_i^* mean economically?

  1. The amount of resource ii used
  2. The rate at which the optimum improves per unit increase of bib_i, while the optimal basis stays the same
  3. The cost of variable ii
  4. The number of pivots