A workshop that builds 42 tables and 24 chairs a week earns $4,140, the most its three limits allow. The simplex method finds that plan in two pivots. It walks from corner to corner of the allowed region.
Learn CLRS Chapter 29: standard and slack form, the simplex method, degeneracy, duality and shadow prices, shortest paths and max flow as LPs, and interior-point methods.
Press Run simplex and watch the walk. Then drag the table profit and run it again. The best corner moves, and so does the path. Then we build the method, piece by piece, from one corner.
You need a little Python and school algebra: straight lines, and inequalities such as 4x + 3y ≤ 240. We build the rest from zero.
Re-taught from Chapter 29, Linear Programming, in the third edition of Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms (CLRS). The workshop and the toys are our own, and a script checked every pivot against scipy.
Illustrative workshop. Limits: carpentry 4 h a table and 3 h a chair, 240 h a week; lumber 3 units and 1 unit, 150 units; finishing 2 h and 4 h, 200 h. The pivot rule is the largest coefficient (Chapter 4).
Chapter 0
Draw the plans a workshop can make, and see why the best one is a corner
You run a small workshop. A table earns $70 and a chair earns $50. Three resources run out each week:
| Resource | Per table | Per chair | Each week |
|---|---|---|---|
| Carpentry hours | 4 | 3 | 240 |
| Lumber units | 3 | 1 | 150 |
| Finishing hours | 2 | 4 | 200 |
How many tables and chairs should you build? Call the number of tables x1 and the number of chairs x2. Each plan is one point on a plane.
Drag the dot. It turns red when the plan breaks a limit. The dashed line holds every plan with the same profit.
Illustrative workshop. Fractions of a table are allowed here; the end of this chapter says why that matters.
Each limit is a straight line, and the allowed side is a half of the plane. The plans that obey all limits form the feasible region: here a teal polygon with five corners. The thing you maximize, 70x1 + 50x2, is the objective. A problem with a straight-line objective and straight-line limits is a linear program (LP).
Now look at the dashed line. Every plan on it earns the same profit. Push it outward and the profit grows. The last point of the region it touches is the best plan. A straight line leaving a polygon with straight sides last touches a corner (a vertex), or a whole side that ends in corners. The best plan is the corner (42, 24): 70 × 42 + 50 × 24 = $4,140.
The region has no dents: it is convex. So a plan with no better neighbour is the best of all. That is why a walk that only goes uphill, from corner to corner, can find the optimum.
The symptom is a search that never ends: try every corner of a large LP. To measure it, count the candidates. Two variables and three limits give at most 10. A hundred variables and two hundred limits give up to C(300, 100), about 4 × 1081. The fix is the simplex method: visit only corners that raise the profit.
Chapter 1
Rewrite any LP as maximize, at-most limits, and no negative variables
You can write one LP many ways: minimize or maximize, at most or at least, equal signs, variables that may go negative. An algorithm wants one fixed shape. CLRS calls it standard form: maximize, every limit is "at most", and every variable is zero or more.
Put the profit per unit in a list c and the amounts you choose in a list x. Put the resource use per unit in a table A, and the supplies in a list b.
Maximize c-transpose x, subject to A x at most b, and x at least zero.
Pick amounts x. Row by row, the use A x must not pass the supply b. Among those plans, take the one with the largest profit cTx.
The workshop: c = (70, 50), b = (240, 150, 200). For x = (42, 24), cTx = 2,940 + 1,200 = 4,140. Row one of A is (4, 3): 4 × 42 + 3 × 24 = 240, exactly the supply.
Four rewrites bring any LP to this shape. None changes the best plan.
Press Next rule. Blue marks the line that changed.
A made-up LP. scipy gives the same best plan before and after: x1 = 6, x2 = 4.
The symptom is a simplex run that cannot start. It starts at the plan x = 0, and that plan breaks a limit whenever some bi is negative. Above, b = (10, −10, −2). The fix in CLRS is an auxiliary LP: add one variable x0 and subtract it from every left side, so A x − x0 ≤ b. Then minimize x0. With x0 large, x = 0 is allowed, so this LP can start.
If the smallest x0 is 0, the original LP has a feasible plan, and simplex starts there. Above, it reaches x0 = 0 at (6, 4). For the limits x1 + x2 ≤ 1 and x1 + x2 ≥ 3, x0 cannot go below 1, so no plan exists: the LP is infeasible.
Chapter 2
Give each limit a slack variable, and find the corners by setting two variables to zero
Algebra is easier with equations than with "at most". So give each limit a new variable that holds the leftover. Call the leftover of resource i its slack, si. Call the supply bi and the use per unit of product j, aij.
s-i equals b-i minus the sum over j of a-i-j times x-j.
For resource i, multiply each amount xj by its use aij and add. Take that from the supply bi. What remains is si. The limit holds exactly when si is zero or more.
Plan (30, 30), carpentry: s1 = 240 − 4 × 30 − 3 × 30 = 30 hours left. Lumber: s2 = 150 − 90 − 30 = 30. Finishing: s3 = 200 − 60 − 120 = 20.
Now the workshop has 5 variables (x1, x2, s1, s2, s3) and 3 equations. Set any 2 of them to zero, the nonbasic variables, and the 3 equations fix the other 3, the basic variables. The result is a basic solution. If every value is zero or more, it is a basic feasible solution, and it is a corner of the region.
Pick a pair. The bars show all five values. A negative bar means the point breaks a limit.
There are C(5, 2) = 10 pairs. Five give corners; five give points outside the region.
Setting si = 0 means the plan sits on line i. Setting xj = 0 means it sits on an axis. So each pair picks two lines and their crossing. The simplex method moves from one basic feasible solution to the next by swapping one variable in the pair.
The symptom is a "corner" that looks better than the best. Lumber and finishing cross at (40, 30), with profit $4,300. To measure it, compute every slack: s1 = 240 − 160 − 90 = −10. The plan needs 10 carpentry hours you do not have. The fix is to keep every value at zero or more on each move. The ratio test in Chapter 3 does that.
Chapter 3
Raise one variable until the first slack hits zero, then swap the two
Start at the corner (0, 0): build nothing, all slacks full. The profit is z = 70x1 + 50x2. Both coefficients are positive, so raising either variable helps. The variable you raise is the entering variable. Take x1, and keep x2 at 0.
As x1 grows, every slack shrinks: s1 = 240 − 4x1, s2 = 150 − 3x1, s3 = 200 − 2x1. You must stop when the first one hits zero. That slack is the leaving variable. Call the entering variable e, and the use per unit of e in row i, aie.
Pick the entering variable and press Raise. Each bar is how far that limit lets it go. The shortest bar wins.
Illustrative workshop. Each ratio is supply divided by use per unit.
t equals the minimum, over the rows i where a-i-e is above zero, of b-i over a-i-e.
For each row with aie above zero, divide bi by aie. That is how far e can rise before row i's variable hits zero. Take the smallest as t. That row's variable leaves.
Raising x1: 240 / 4 = 60, 150 / 3 = 50, 200 / 2 = 100. So t = 50 and lumber s2 leaves. The plan moves to (50, 0) and the profit to 70 × 50 = $3,500.
The pivot rewrites the equations around the new corner. Solve the lumber row for x1: x1 = 50 − x2/3 − s2/3. Put that into the profit:
Now x1 is basic and s2 is nonbasic. The profit still has a positive coefficient, 80/3 on x2, so another pivot can help.
The symptom is a ratio test with no rows: every aie is zero or negative. Nothing stops e, so the profit has no ceiling: the LP is unbounded.
Example: maximize x1 with only x1 − x2 ≤ 5. Raise both together and the profit grows forever. To measure it, check the entering column for a positive entry. The fix is in the model: a limit is missing.
Chapter 4
Pivot until every coefficient in the profit row is negative or zero
The simplex method (George Dantzig, 1947) repeats the pivot. Pick a nonbasic variable with a positive profit coefficient. Run the ratio test. Swap. When no coefficient is positive, stop. A tableau is the table that stores the equations: one row per basic variable, one column per variable, plus the profit row.
Press Pivot. The entering column is blue; the leaving row is purple. Then switch the rule and walk again.
The profit row shows each coefficient c̄j as the tableau stores it, with its sign flipped: a negative entry there means "raising this helps". Values are exact fractions.
With the largest-coefficient rule the walk takes two pivots. After the first, z = 3,500 + (80/3)x2 − (70/3)s2. Now x2 enters. The ratios are 40/(5/3) = 24 for carpentry, 50/(1/3) = 150 for lumber and 100/(10/3) = 30 for finishing. Carpentry leaves, and the plan reaches (42, 24).
Write the profit using only the nonbasic variables. Call the constant part v, and the coefficient of nonbasic variable j its reduced cost, c̄j (read "c-bar-j").
z equals v plus the sum, over the nonbasic j, of c-bar-j times x-j.
Read each c̄j. If one is positive, raising that xj raises z: pivot on it. If every c̄j is zero or negative, no move helps, and v is the best profit.
At (42, 24): z = 4,140 − 16s1 − 2s2. So v = 4,140, c̄ = −16 for carpentry slack and −2 for lumber slack. Leaving an hour idle costs $16; leaving a unit of lumber costs $2. Stop: $4,140 is optimal.
The other rule enters x2 first and walks (0, 0) → (0, 50) → (36, 32) → (42, 24). Three pivots, same answer. The rule changes the path, never the result.
The symptom is a loop that never stops in floating point. A coefficient that should be 0 comes out as −1 × 10−15, and the code keeps pivoting on it. To measure it, count pivots and print the profit row. The fix is a tolerance: treat any value within 10−9 of zero as zero.
Chapter 5
See a pivot that does not move, a loop of bases, and a walk through every corner
Take a smaller LP: maximize x1 + x2 with x1 + x2 ≤ 4, 2x1 + x2 ≤ 6 and x1 + 2x2 ≤ 6. All three lines pass through (2, 2). A corner where more lines meet than the number of variables is degenerate.
Pick a case and press Pivot. Watch the ratio test on the tied corner, and count the corners on the square.
Both LPs are small textbook-style examples; every pivot is computed live and was checked in exact fractions.
From (3, 0), x2 enters and the ratio test ties: row 1 gives 1/(1/2) = 2 and row 3 gives 3/(3/2) = 2. One slack leaves. The other stays basic with value 0. Any later pivot on that zero row has t = 0: the basis changes, the point does not. That is a degenerate pivot.
A run of degenerate pivots can come back to a basis it has seen. Then simplex cycles forever. A classic 4-variable example (in Chvátal's textbook) cycles every 6 pivots under the largest-coefficient rule. Bland's rule (1977) breaks every tie by the smallest index, for the entering and the leaving variable. It cannot cycle. On that example it stops after 7 pivots.
Klee and Minty (1972) built LPs that force a long walk. In d dimensions the region is a squashed cube with 2d corners, and the largest-coefficient rule visits all of them:
| Dimensions d | Corners 2d | Pivots, largest coefficient |
|---|---|---|
| 2 | 4 | 3 |
| 3 | 8 | 7 |
| 6 | 64 | 63 |
| d | 2d | 2d − 1 |
On real LPs simplex is fast. Spielman and Teng's smoothed analysis (2001) gives one reason: add small random noise to the numbers and the expected number of pivots becomes polynomial. Nobody has found a pivot rule that is proven polynomial on every LP.
The symptom is a profit that stays flat for many pivots. To measure it, store each basis as a sorted tuple and check for a repeat. The fix is Bland's rule, or a tiny random change to b that removes the ties.
Chapter 6
Price the resources so no product pays more, and that price caps your profit
A buyer wants all your resources for the week. She offers y1 dollars per carpentry hour, y2 per lumber unit and y3 per finishing hour. You sell only if the resources in a table are worth at least the table's $70, and the same for a chair's $50:
This is the dual LP. The workshop problem is the primal. In matrix form the dual is: minimize bTy subject to ATy ≥ c and y ≥ 0. The table A turns on its side; supplies and profits swap places.
Move the prices. Each product bar must reach its profit line. Then the offer is a ceiling on any plan's profit.
Illustrative workshop. The best primal profit, $4,140, is the dashed line.
Why is any covering offer a ceiling? Call the plan x and the prices y.
c-transpose x is at most b-transpose y.
At prices y, each product earns at most what its resources cost. So the profit cTx is at most the cost of the resources the plan uses, yTAx. The plan uses at most the supply, so that cost is at most bTy.
Plan (36, 32) earns 4,120. Prices (0, 18, 8) cover both products (70 and 50 exactly) and offer 150 × 18 + 200 × 8 = 4,300. Prices (16, 2, 0) offer 3,840 + 300 = 4,140. So no plan beats 4,140, and the plan (42, 24) reaches it.
Strong duality says more: if the primal has a best plan, the dual has best prices, and the two values are equal. Here both are $4,140. CLRS proves it from the final simplex tableau, which holds the best prices in its profit row (the 16 and 2 of Chapter 4).
The symptom is a "ceiling" below a plan you can build: prices (10, 0, 0) offer $2,400, but plan (42, 24) earns $4,140. To measure it, check ATy ≥ c: a table's resources are worth only 40, short of 70. The fix: only covering prices give a ceiling.
Chapter 7
Read what one more unit of each resource is worth, and why a leftover resource is free
The best prices are y = (16, 2, 0). Each is a shadow price: the extra profit from one more unit of that resource. Lumber is worth $2 a unit to you. Finishing is worth nothing, because 20 hours of it are already idle.
Drag the lumber supply. One panel shows the region and the best plan. The other plots best profit against lumber; its slope is the shadow price.
Illustrative workshop; every point of the curve is a fresh solve. scipy agrees at 100, 120, 140, 160 and 180.
The curve has three straight pieces. Between 140 and 180 units the slope is 2. Below 140 lumber gets scarcer and the slope is 18. Above 180 carpentry runs out and more lumber is worth 0.
Why is idle finishing free? Call the leftover of resource i its slack, bi − aix, where ai is row i of A.
y-i times, b-i minus a-i x, equals zero.
For each resource, either the plan uses all of it, or its price yi is zero. A product made in positive amount pays exactly its resource cost.
Carpentry: 16 × (240 − 240) = 0. Lumber: 2 × (150 − 150) = 0. Finishing: 0 × (200 − 180) = 0. Tables: 4 × 16 + 3 × 2 = 70, exactly the profit, as it must be since x1 = 42 > 0.
So a shadow price answers "should I buy more?". If a carpenter rents at $10 an hour and the shadow price is $16, each hour adds $6, up to 250 hours. Past that the basis changes and the price drops.
The symptom is a forecast that overshoots. Buy 50 more lumber at a shadow price of $2 and you predict +$100. The real gain is +$60, from $4,140 to $4,200. To measure it, re-solve at the new supply. The fix: a shadow price holds only inside its range, here 140 to 180 units.
Chapter 8
Write two graph problems as LPs, and see max-flow min-cut as duality
CLRS section 29.2 writes graph problems as LPs. Start with a shortest path from s to t. Give each vertex v a number dv, its distance from s. Call the weight of the edge from u to v w(u, v).
d-v is at most d-u plus w of u, v, for every edge from u to v.
Each edge caps dv at du plus the edge's weight. Push dt as high as the caps allow. The tightest chain of caps is the shortest path.
Made-up weights: s→a 2, s→b 5, a→b 1, a→t 6, b→t 2. Then da ≤ 2, db ≤ min(5, 2 + 1) = 3, dt ≤ min(2 + 6, 3 + 2) = 5. scipy returns dt = 5, the path s, a, b, t.
Why maximize? The limits are upper caps, so only maximizing presses dt against them. Minimize dt and scipy reports the LP as unbounded.
Maximum flow is an LP too. Give each edge a flow f(u, v). Keep 0 ≤ f(u, v) ≤ c(u, v), its capacity. At each inner vertex, flow in equals flow out. Maximize the flow out of s.
Drag the capacity of a→t. Blue numbers are the flows the LP finds. Purple marks the smallest cut: its source side and the edges that leave it.
Made-up capacities. The flow comes from augmenting paths; scipy's LP gives the same value for every setting.
The dual of the max-flow LP is a cut LP. At its best, it picks a set of vertices with s inside and t outside, and pays the capacity of every edge leaving the set. So max-flow equals min-cut is strong duality on one graph. Capacity 2 gives flow 8 and the cut {s, a} paying 4 + 2 + 2 = 8.
The symptom is a flow larger than the network can carry. Drop the "in equals out" rule at a, and the LP reports 9 with capacity a→t at 0, where the true maximum is 6. To measure it, add in and out at every inner vertex. The fix: one equation per inner vertex.
Chapter 9
Replace hard walls with a soft push, and slide along the central path to the corner
Simplex walks the edges. Two other methods solve every LP in polynomial time. The ellipsoid method (Khachiyan, 1979) proved it possible, but it is slow in practice. Interior-point methods (Karmarkar, 1984) are polynomial and fast. They move through the inside of the region.
Replace each wall with a soft push. Call the slack of each limit slacki, including x1 and x2 themselves. Call the push strength μ (mu).
Maximize c-transpose x plus mu times the sum over i of the natural log of slack-i.
Add μ times the log of every slack to the profit. Find the best plan of that smooth problem with Newton's method. Shrink μ and repeat from there. The best points trace the central path to the optimal corner.
With μ = 100 the best point is (38.0, 25.5), profit $3,936. On the central path the gap to the optimum is at most 5 × μ = 500; here it is 204. With μ = 1 the point is (41.7, 24.3) and the gap is 2.
Drag μ down. The yellow point is the best plan of the barrier problem. Blue is simplex's edge walk, for contrast.
Illustrative workshop. Each point is a live Newton solve; scipy matches it to 3 decimals at μ = 10,000, 1,000, 100, 10, 1 and 0.1.
| Method | Year | Worst case | Where it moves |
|---|---|---|---|
| Simplex | 1947 | Exponential (Klee-Minty) | Corner to corner |
| Ellipsoid | 1979 | Polynomial | Shrinking ellipsoids |
| Interior point | 1984 | Polynomial | The central path |
The symptom is an answer that sits near a corner but not on it, such as (41.7, 24.3). To measure it, look at the slacks: none is exactly zero. The fix is to shrink μ until the gap bound is below your tolerance, then snap to the nearest corner, a step solvers call crossover.
Chapter 10
Keep the terms, the numbers, the checks and the code in one place
An LP maximizes a straight-line objective over a convex region cut by straight-line limits, so a corner is optimal. Simplex walks corners by pivots and stops when no reduced cost is positive. The dual prices the limits, and its best value equals the primal's.
| Term | Meaning |
|---|---|
| Standard form | Maximize cTx, A x ≤ b, x ≥ 0 |
| Slack form | Each limit as an equation with a slack si ≥ 0 |
| Basic feasible solution | n variables set to 0, the rest solved and all ≥ 0: a corner |
| Pivot | One variable enters, the ratio test picks one to leave |
| Reduced cost c̄j | Profit per unit from raising nonbasic xj; stop when all ≤ 0 |
| Degenerate corner | More limits meet than there are variables; pivots may not move |
| Dual | Minimize bTy, ATy ≥ c, y ≥ 0 |
| Shadow price | Best dual value yi: profit per extra unit of resource i, inside its range |
| What | Number | Why it matters |
|---|---|---|
| Workshop optimum | (42, 24), $4,140 | Carpentry and lumber bind |
| Simplex path | (0, 0) → (50, 0) → (42, 24) | Two pivots, largest coefficient |
| Final profit row | 4,140 − 16s1 − 2s2 | Optimal, and the dual prices |
| Dual prices | (16, 2, 0), $4,140 | Strong duality |
| Lumber shadow price | $2, from 140 to 180 units | Outside the range it changes |
| Klee-Minty, d dimensions | 2d − 1 pivots | Simplex is exponential in the worst case |
| Max flow, cap a→t = 2 | 8 = cut {s, a} | Max-flow min-cut is duality |
| Barrier, μ = 100 | (38.0, 25.5), gap 204 ≤ 500 | Gap at most (walls) × μ |
pythonimport numpy as np from scipy.optimize import linprog def simplex(c, A, b, eps=1e-9): """Maximize c @ x subject to A @ x <= b, x >= 0. Needs b >= 0.""" m, n = A.shape T = np.hstack([A, np.eye(m), b.reshape(-1, 1)]).astype(float) z = np.concatenate([-c, np.zeros(m + 1)]).astype(float) # profit row, signs flipped basis = list(range(n, n + m)) # start: slacks are basic while z[:-1].min() < -eps: # some reduced cost > 0 e = int(np.argmin(z[:-1])) # largest coefficient enters col = T[:, e] ratios = np.where(col > eps, T[:, -1] / np.where(col > eps, col, 1), np.inf) if np.isinf(ratios).all(): raise ValueError("unbounded") l = int(np.argmin(ratios)) # ratio test: row that leaves T[l] /= T[l, e] for i in range(m): if i != l: T[i] -= T[i, e] * T[l] z -= z[e] * T[l] basis[l] = e x = np.zeros(n + m) x[basis] = T[:, -1] y = z[n:n + m] # dual prices under the slacks return x[:n], z[-1], y c = np.array([70, 50]); A = np.array([[4, 3], [3, 1], [2, 4]]); b = np.array([240, 150, 200]) print(simplex(c, A, b)) # x = [42, 24], z = 4140, y = [16, 2, 0] res = linprog(-c, A_ub=A, b_ub=b, method="highs") # linprog minimizes: negate c print(res.x, -res.fun, -res.ineqlin.marginals) # [42. 24.] 4140.0 [16. 2. 0.]
LP solves in polynomial time, but no algorithm is known whose step count depends only on the number of variables and limits (a strongly polynomial one). Add "whole numbers only" and the problem becomes NP-hard. Some LPs, such as max flow with whole capacities and bipartite matching, have whole-number corners anyway, so the LP answer is already whole.
Now press Present or Teach. Explain from memory why the best plan is a corner, how one pivot works, how to read the final profit row, and why the dual is a ceiling. Then go back to the hero, set the table profit to $140, and say why the walk ends at the same corner.
This lesson re-teaches Chapter 29, Linear Programming, in the third edition of Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms: standard and slack forms (29.1), formulating problems as LPs (29.2), the simplex algorithm (29.3), duality (29.4) and the initial basic feasible solution (29.5). The workshop, the networks and the toys are our own; every number was checked with scipy.optimize.linprog and exact fractions.