The Simplex Method as a Walk on Vertices
The previous lesson showed that an optimum sits at a vertex and that vertices are basic feasible solutions. The simplex method (Dantzig, 1947) turns this into an algorithm: start at a vertex, and repeatedly move along an edge of the polytope to a neighbouring vertex with a better objective value, until no neighbour is better. Algebraically, each move exchanges one basic variable for one non-basic variable, a pivot. This lesson implements the method in exact arithmetic with Bland's rule, prints every tableau, and checks that each pivot really is a step along an edge. The matrix-form derivation and phase I are in The Simplex Method; here the focus is on the walk and on what it guarantees.
Dictionaries and tableaux
Take with , so that the origin is a vertex (all slacks basic). In general, for a basis the equations can be solved for the basic variables in terms of the non-basic ones:
Here is the full matrix with slack columns, and are the reduced costs. Setting gives the current vertex with value . A tableau stores exactly these numbers: one row per basic variable and an objective row with the reduced costs.
- If for every non-basic , no non-basic variable can increase : the vertex is optimal. (The reduced costs then give an optimal dual solution, as the duality section shows.)
- Otherwise pick an entering variable with . Increasing from zero while the other non-basic variables stay zero moves along an edge of the polytope. The basic variables change linearly; the first one to reach zero leaves the basis (the ratio test). If none ever reaches zero, the LP is unbounded along this edge.
SIMPLEX(tableau T, basis B) -- b >= 0, slack basis to start
1 loop
2 E = { j non-basic : reduced cost r_j > 0 }
3 if E is empty: return the vertex of B -- optimal
4 e = min E -- Bland: smallest index
5 R = { i : T[i][e] > 0 }
6 if R is empty: return UNBOUNDED -- the edge is a ray
7 l = argmin over i in R of T[i][rhs] / T[i][e] -- ties: smallest basic index
8 PIVOT(T, l, e): divide row l by T[l][e], eliminate column e elsewhere
9 replace B[l] by eBland's rule (Bland, 1977) always takes the entering variable with the smallest index among the improving ones and, among tied rows in the ratio test, the leaving variable with the smallest index. It is not fast, but it never cycles, so the method always terminates; the next lesson shows that the popular "largest reduced cost" rule can cycle forever.
An implementation with tableau printouts
The program solves
with Fraction entries, so that the tableaux are exact. Each tableau shows the basis, the rows, and the objective row z with the reduced costs and minus the current value in the right-hand column.
from fractions import Fraction as F
def show(T, z, basis, cols):
print(" " + "".join(f"{c:>6}" for c in cols) + " rhs")
for i, row in enumerate(T):
print(f" {cols[basis[i]]:>4} " + "".join(f"{str(v):>6}" for v in row[:-1]) + f" {str(row[-1]):>4}")
print(" z " + "".join(f"{str(v):>6}" for v in z[:-1]) + f" {str(z[-1]):>4}")
def simplex(c, A, b, names, verbose=True):
m, n = len(A), len(c)
T = [[F(v) for v in A[i]] + [F(int(i == k)) for k in range(m)] + [F(b[i])] for i in range(m)]
z = [F(v) for v in c] + [F(0)] * (m + 1)
basis = [n + i for i in range(m)]
cols = names + [f"s{i + 1}" for i in range(m)]
path = []
while True:
x = [F(0)] * (n + m)
for i, j in enumerate(basis):
x[j] = T[i][-1]
path.append((tuple(x[:n]), -z[-1]))
if verbose:
show(T, z, basis, cols)
improving = [j for j in range(n + m) if z[j] > 0]
if not improving:
return "optimal", path
e = min(improving) # Bland: smallest index enters
rows = [i for i in range(m) if T[i][e] > 0]
if not rows:
return "unbounded", path
l = min(rows, key=lambda i: (T[i][-1] / T[i][e], basis[i])) # ratio test, ties by index
if verbose:
print(f"pivot: {cols[e]} enters, {cols[basis[l]]} leaves\n")
piv = T[l][e]
T[l] = [v / piv for v in T[l]]
for i in range(m):
if i != l and T[i][e] != 0:
f = T[i][e]
T[i] = [a - f * p for a, p in zip(T[i], T[l])]
f = z[e]
z = [a - f * p for a, p in zip(z, T[l])]
basis[l] = e
status, path = simplex([1, 2, 4], [[1, 1, 2], [2, 0, 1], [2, 1, 3]], [4, 5, 7], ["x1", "x2", "x3"])
print(status)
for x, val in path:
print("vertex", tuple(str(v) for v in x), "value", val) x1 x2 x3 s1 s2 s3 rhs
s1 1 1 2 1 0 0 4
s2 2 0 1 0 1 0 5
s3 2 1 3 0 0 1 7
z 1 2 4 0 0 0 0
pivot: x1 enters, s2 leaves
x1 x2 x3 s1 s2 s3 rhs
s1 0 1 3/2 1 -1/2 0 3/2
x1 1 0 1/2 0 1/2 0 5/2
s3 0 1 2 0 -1 1 2
z 0 2 7/2 0 -1/2 0 -5/2
pivot: x2 enters, s1 leaves
x1 x2 x3 s1 s2 s3 rhs
x2 0 1 3/2 1 -1/2 0 3/2
x1 1 0 1/2 0 1/2 0 5/2
s3 0 0 1/2 -1 -1/2 1 1/2
z 0 0 1/2 -2 1/2 0 -11/2
pivot: x3 enters, x2 leaves
x1 x2 x3 s1 s2 s3 rhs
x3 0 2/3 1 2/3 -1/3 0 1
x1 1 -1/3 0 -1/3 2/3 0 2
s3 0 -1/3 0 -4/3 -1/3 1 0
z 0 -1/3 0 -7/3 2/3 0 -6
pivot: s2 enters, x1 leaves
x1 x2 x3 s1 s2 s3 rhs
x3 1/2 1/2 1 1/2 0 0 2
s2 3/2 -1/2 0 -1/2 1 0 3
s3 1/2 -1/2 0 -3/2 0 1 1
z -1 0 0 -2 0 0 -8
optimal
vertex ('0', '0', '0') value 0
vertex ('5/2', '0', '0') value 5/2
vertex ('5/2', '3/2', '0') value 11/2
vertex ('2', '0', '1') value 6
vertex ('0', '0', '2') value 8
The walk visits five vertices, and the value goes . In the final tableau every reduced cost is non-positive, which proves optimality: , and the non-basic variables cannot go below zero. Bland's rule is short-sighted here: it enters first because it has the smallest index, although has the largest reduced cost. Dantzig's original rule (enter the largest reduced cost) pivots in at once and reaches the optimum in a single pivot. Neither rule is better on all inputs.
Every pivot is an edge
Two bases are adjacent if they differ in exactly one element. Their basic solutions are either the same point (a degenerate pivot) or the two endpoints of an edge of the polytope: along the segment between them, the constraints tight at both stay tight, which is the definition of an edge (a one-dimensional face). The program checks this for the path above, counting for each step the constraints, among the three rows and three sign constraints, that are tight at both endpoints.
from fractions import Fraction as F
A = [[1, 1, 2], [2, 0, 1], [2, 1, 3]]
b = [4, 5, 7]
path = [(0, 0, 0), (F(5, 2), 0, 0), (F(5, 2), F(3, 2), 0), (2, 0, 1), (0, 0, 2)]
def tight(x):
rows = {f"row{i + 1}" for i in range(3) if sum(a * v for a, v in zip(A[i], x)) == b[i]}
return rows | {f"x{j + 1}>=0" for j in range(3) if x[j] == 0}
for p, q in zip(path, path[1:]):
common = sorted(tight(p) & tight(q))
mid = tuple((F(u) + F(v)) / 2 for u, v in zip(p, q))
print(f"{tuple(str(v) for v in p)} -> {tuple(str(v) for v in q)}: common tight {common}, midpoint tight {sorted(tight(mid))}")('0', '0', '0') -> ('5/2', '0', '0'): common tight ['x2>=0', 'x3>=0'], midpoint tight ['x2>=0', 'x3>=0']
('5/2', '0', '0') -> ('5/2', '3/2', '0'): common tight ['row2', 'x3>=0'], midpoint tight ['row2', 'x3>=0']
('5/2', '3/2', '0') -> ('2', '0', '1'): common tight ['row1', 'row2'], midpoint tight ['row1', 'row2']
('2', '0', '1') -> ('0', '0', '2'): common tight ['row1', 'x2>=0'], midpoint tight ['row1', 'x2>=0']
Each step keeps two constraints tight (one less than the dimension, 3), and the midpoint of each step has exactly those two tight: the step runs along an edge. Note that the third and fourth steps change two coordinates at once; an edge need not be parallel to an axis.
In C++
The same method with a small exact fraction type (64-bit numerator and denominator, reduced by the gcd after every operation, which is safe for these tiny inputs). It prints one line per pivot instead of the tableaux.
#include <cstdio>
#include <numeric>
#include <string>
#include <vector>
struct Q { // exact rational p/q, q > 0
long long p, q;
Q(long long a = 0, long long b = 1) : p(a), q(b) { norm(); }
void norm() { 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); }
Q operator/(Q o) const { return Q(p * o.q, q * o.p); }
bool operator<(Q o) const { return p * o.q < o.p * q; }
std::string str() const { return q == 1 ? std::to_string(p) : std::to_string(p) + "/" + std::to_string(q); }
};
int main() {
std::vector<std::vector<long long>> A = {{1, 1, 2}, {2, 0, 1}, {2, 1, 3}};
std::vector<long long> b = {4, 5, 7}, c = {1, 2, 4};
int m = 3, n = 3, w = n + m + 1;
std::vector<std::vector<Q>> T(m, std::vector<Q>(w));
std::vector<Q> z(w);
std::vector<int> basis(m);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) T[i][j] = Q(A[i][j]);
T[i][n + i] = Q(1);
T[i][w - 1] = Q(b[i]);
basis[i] = n + i;
}
for (int j = 0; j < n; j++) z[j] = Q(c[j]);
auto name = [&](int j) { return (j < n ? "x" : "s") + std::to_string(j < n ? j + 1 : j - n + 1); };
for (int it = 1;; it++) {
int e = -1;
for (int j = 0; j < n + m && e < 0; j++) if (Q(0) < z[j]) e = j; // Bland: first improving column
if (e < 0) break;
int l = -1;
for (int i = 0; i < m; i++) {
if (!(Q(0) < T[i][e])) continue;
if (l < 0) { l = i; continue; }
Q ri = T[i][w - 1] / T[i][e], rl = T[l][w - 1] / T[l][e];
if (ri < rl || (!(rl < ri) && basis[i] < basis[l])) l = i;
}
if (l < 0) { std::printf("unbounded\n"); return 0; }
std::printf("pivot %d: %s enters, %s leaves", it, name(e).c_str(), name(basis[l]).c_str());
Q piv = T[l][e];
for (auto& v : T[l]) v = v / piv;
for (int i = 0; i < m; i++)
if (i != l) { Q f = T[i][e]; for (int j = 0; j < w; j++) T[i][j] = T[i][j] - f * T[l][j]; }
Q f = z[e];
for (int j = 0; j < w; j++) z[j] = z[j] - f * T[l][j];
basis[l] = e;
std::printf(", value now %s\n", (Q(0) - z[w - 1]).str().c_str());
}
std::vector<Q> x(n + m);
for (int i = 0; i < m; i++) x[basis[i]] = T[i][w - 1];
std::printf("optimal: x = (%s, %s, %s), value %s\n", x[0].str().c_str(), x[1].str().c_str(), x[2].str().c_str(),
(Q(0) - z[w - 1]).str().c_str());
}pivot 1: x1 enters, s2 leaves, value now 5/2
pivot 2: x2 enters, s1 leaves, value now 11/2
pivot 3: x3 enters, x2 leaves, value now 6
pivot 4: s2 enters, x1 leaves, value now 8
optimal: x = (0, 0, 2), value 8
How many pivots?
Each pivot costs arithmetic operations on the tableau, so the question is the number of pivots. In practice it is usually a small multiple of . In the worst case, no pivoting rule is known to need only polynomially many pivots: Klee and Minty (1972) built cubes on which Dantzig's rule visits all vertices, and similar constructions exist for Bland's rule and most other deterministic rules (Klee-Minty Cubes and Smoothed Analysis). Whether some rule is polynomial is open; it would need the graph of every polytope to have polynomial diameter (the polynomial Hirsch conjecture). The original Hirsch conjecture, diameter at most for facets in dimension , was disproved by Santos (2012), but the known counterexamples exceed the bound only by a small factor.
Note: Phase I. When the origin is not feasible. The standard fix solves an auxiliary LP that minimizes the total violation (an artificial variable per bad row) starting from an obvious vertex; its optimum is 0 exactly when the original LP is feasible, and its final basis is a starting vertex for phase II.
Test yourself
In a maximization tableau, when does the simplex method stop with an optimal vertex?
- When some reduced cost is positive
- When every reduced cost of a non-basic variable is
- When all basic variables are positive
- After pivots
The entering column has no positive entry. What does the simplex method conclude?
- The current vertex is optimal
- The LP is unbounded: the entering variable can grow forever along a ray
- The LP is infeasible
- It must switch to Bland's rule
What is the geometric meaning of a non-degenerate pivot?
- A jump to a random vertex
- A move along an edge of the polytope to an adjacent vertex
- A step into the interior
- A reflection of the polytope
What does Bland's rule guarantee?
- A polynomial number of pivots
- Termination: the method never cycles
- The fewest possible pivots
- An integral optimum