Optimization
How do you find the best choice, and how do you prove that nothing better exists?
In 1945 Stigler found a diet for 39.93 dollars a year by insight; two years later Laderman's team worked Dantzig's simplex method by hand and found 39.69, with a proof that no diet is cheaper. The part builds that method on Chvatal's three-product linear program: a polytope with six vertices, a walk of two pivots to a profit of 13, and dual prices (1, 0, 1) that certify it. It then asks how long the walk can be: Dantzig's rule takes 2^n - 1 pivots on Klee and Minty's cubes, while ellipsoids and the central path give polynomial bounds. Total unimodularity explains when the vertices are integers; when they are not, branch and bound uses the relaxation as a guide. For NP-hard problems the part proves how close a fast algorithm can get: factor 2 for vertex cover, H_n for set cover, 3/2 for metric tours, 0.878 for MAX-CUT by a random hyperplane. It ends with decisions made without the future (ski rental, paging), multiplicative weights, convex optimization in a page, and three open questions: strongly polynomial LP, the polynomial Hirsch conjecture and the Unique Games Conjecture.
What you need. Linear algebra: Gaussian elimination, matrix-vector products and determinants; the gradient of a function of several variables for chapter 13.
- Mathematics, ideas and history
- LP geometry, simplex, duality, Klee–Minty, ellipsoid and interior point, total unimodularity, approximation (Christofides, Goemans–Williamson), online algorithms, multiplicative weights
- What we build or compute
- a simplex solver; TSP heuristics
What you will be able to do
Degree
- Model a small planning problem as a linear program and solve it by pivoting a simplex tableau.
- Write the dual of a linear program and use a dual solution to prove that a primal solution is optimal.
- Prove the factor-2 guarantee for vertex cover and the competitive ratio of the break-even rule for ski rental.
Graduate
- Prove weak duality, state strong duality and Farkas' lemma, and read shadow prices and complementary slackness off an optimal tableau.
- Explain why a totally unimodular constraint matrix with integer right-hand sides gives integer vertices, and why the triangle's matching polytope does not.
- Derive the Goemans-Williamson constant from the probability that a random hyperplane separates two unit vectors, and the regret bound of multiplicative weights from its potential.
Research
- State what smoothed analysis proves about a simplex method and what it does not say about Dantzig's rule on a perturbed cube.
- State the Hirsch conjecture, Santos's counterexample and the open polynomial version, and the approximation thresholds that follow from the Unique Games Conjecture.
Industry
- Solve an integer program by branch and bound with exact bounds, and explain why a nearly integral relaxation is not a feasible answer.
- Report a solver or heuristic result with its certificate: a dual bound, an optimality gap, or a guarantee and the model it assumes.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 20 min · Graduate 42 min · Research 46 min · Industry 23 min.
- 0The best point of a polytopeDegree2 min
- 1Linear programsDegree3 min
- 2The simplex methodDegree3 min
- 3DualityDegree3 min
- 4Exponential in theory, fast in practiceGraduate2 min
- 5Polynomial time: ellipsoids and the central pathGraduate2 min
- 6When the vertices are integersGraduate3 min
- 7Integer programmingIndustry4 min
- 8Approximation: coversDegree3 min
- 9The travelling salesmanGraduate3 min
- 10A random hyperplane: MAX-CUTGraduate3 min
- 11Online: deciding without the futureDegree3 min
- 12Multiplicative weightsGraduate3 min
- 13Convex optimization in a pageGraduate2 min
- 14Frontier: faster LPs, the Hirsch question, the UGCResearch4 min
- Recap, problems, and where this comes backAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
The best point of a polytopeDegree2 min
In 1945 the economist George Stigler asked what it costs, at the least, to feed a person for a year. He had seventy-seven foods and nine nutrients, and a person needs enough of each. By trial and insight he found a diet costing thirty-nine dollars and ninety-three cents a year, at 1939 prices, mostly wheat flour, cabbage and evaporated milk. He wrote that there was no direct way to find the true minimum. Two years later George Dantzig invented one. Jack Laderman's team worked his simplex method by hand on desk calculators, roughly a hundred and twenty person-days of arithmetic, and found thirty-nine sixty-nine. And it came with something Stigler could not have: a proof that no diet is cheaper. That proof, which this part calls duality, is the idea that lasts.
This part is about choosing the best, and about the three kinds of answer we can get. For linear programs, the best point of a polytope, there are fast algorithms and exact answers that come with a proof. For problems with integer choices, like the travelling salesman, the exact answer is NP-hard; we settle for algorithms with proven guarantees, and heuristics that do better than the guarantees promise. And for decisions made without seeing the future, like which page to evict from a cache, we measure ourselves against a clairvoyant who sees everything, and prove we are never too far behind.
1Linear programsDegree3 min
A linear program asks for the largest value of a linear function, subject to linear inequalities. Here is a small one, the first example in Vašek Chvátal's textbook: three products with profits five, four and three, made from three scarce resources, with the amounts each product needs on the left and the supply on the right. In matrix form: maximize c transpose x subject to A x at most b, with x non-negative. Leonid Kantorovich formulated such problems in 1939 to plan a plywood trust in Leningrad. George Dantzig met them in 1947, scheduling for the US Air Force, when programming still meant planning. Kantorovich and Tjalling Koopmans shared the 1975 Nobel prize in economics for this work; Dantzig, famously, did not.
Most of the work of linear programming is modelling: deciding what the variables are. Here is the kind of problem Kantorovich, and independently Frank Hitchcock in 1941, studied. Two plants make thirty and forty units; three stores need twenty, twenty-five and twenty-five; each road has a cost per unit shipped. Use one variable per road, the amount sent along it. Minimize the total cost, subject to each plant's capacity and each store's demand. Serving every store from its cheapest plant would cost three hundred and fifty-five dollars, but it asks plant B for fifty units, and B makes forty. The optimum costs three hundred and sixty-five: store three is split between the two plants, and ten units travel the more expensive road. A handful of tricks bring far more problems into this form. An equation is two inequalities. A variable that may be negative is the difference of two that may not. To minimize the largest of several linear costs, add a variable t, require each cost to be at most t, and minimize t. Absolute values work the same way. That is why so much of operations research is linear programming.
Each linear inequality cuts space in half; their intersection is a convex polyhedron, which may be unbounded. Our particular three-product region is bounded, so it is a polytope, with the coordinate planes among its walls. Exact rational plane intersections give its six vertices. Points with the same profit lie on parallel objective planes. Push a plane towards greater profit until it last touches our region: two units of product one and one of product three, earning thirteen. A nonempty bounded polytope has a vertex attaining the maximum of every linear objective. This gives finitely many candidates, but their number can grow exponentially with the dimension.
2The simplex methodDegree3 min
Dantzig's simplex method walks from vertex to vertex. Our implementation begins at the origin, a feasible slack basis because every right-hand side is nonnegative. Finding an initial feasible basis for arbitrary data needs a separate Phase One, which this teaching code does not implement. Inspect the reduced costs for a feasible improving pivot. Move until a constraint blocks further travel. Here the objective goes from zero to twelve and a half, then thirteen. Nonnegative reduced costs certify global optimality for this maximization tableau. Degenerate bases can require zero-length pivots; merely seeing no immediate positive movement is insufficient. This example reaches an exact primal and dual certificate after two pivots.
In algebra, the walk is a sequence of pivots. Add a slack variable to each inequality, the unused amount of each resource, and the constraints become equations. The slacks themselves form the first basis: the origin, where all resources are unused. The bottom row holds the objective. A negative entry means increasing that variable raises the profit; Dantzig's rule picks the most negative, here the first product. How far can it rise? The ratio test divides each right-hand side by the column's entry and takes the smallest: the first resource runs out first, at two and a half. The pivot is one step of Gaussian elimination, making that column a unit vector. One more pivot brings in the third product, and now the bottom row has no negative entries. The profit is thirteen, and the numbers under the slack columns, one, zero and one, are the prices of the resources, which the next chapter shows are a proof.
Here is an executed stopping-status example. Maximize x between zero and one. With a zero pivot budget our code returns the feasible origin and reports iteration limit, not optimal. The incumbent earns zero, while the true optimum is one. Its zero dual multiplier does not cover the objective coefficient one. A feasible primal answer alone cannot certify optimality. Allow one pivot. The returned primal x and dual y both equal one; both are feasible, and their equal objectives certify the optimum. The budget status and the certificate now agree.
Which pivot should the walk take? Dantzig chooses the largest improving reduced-cost coefficient; this is not a normalized geometric slope. At a degenerate vertex a pivot can change the basis without moving, and unsuitable choices can cycle. Bland's smallest eligible index rule prevents cycling in exact arithmetic. Our full tableau updates all m times n plus m entries at each pivot. Production revised simplex maintains basis factorizations. Its normalized steepest-edge rules differ from our selector called greatest improvement, which tests the whole gain of each candidate pivot. A small number of pivots in one example gives no polynomial worst-case guarantee; the next chapters examine that distinction.
3DualityDegree3 min
How could anyone prove that thirteen is the best possible profit? Multiply each constraint by a non-negative number and add them up. If the combined left side has at least the objective's coefficients, five, four and three, then for any feasible plan the profit is at most the combined right side. Three times the first constraint gives six, nine and three, which covers five, four and three, so the profit is at most fifteen. Five thirds of the third constraint proves thirteen and a third. Five quarters of the second fails: it doesn't cover the coefficients of the second and third products. And one of the first plus one of the third proves exactly thirteen. Finding the best bound is itself a linear program, the dual: minimize five y one plus eleven y two plus eight y three, subject to the covering conditions.
Every linear program has a dual. Our primal maximizes over nonnegative x with A x at most b; its dual minimizes b transpose y with nonnegative y and A transpose y at least c. Weak duality holds for every feasible pair. If the primal is feasible with a finite optimum, strong duality gives an attained equal dual optimum. This does not say that every infeasible or unbounded program has an optimal pair. One form of Farkas' lemma says exactly one alternative holds: A x equals b for some nonnegative x, or a vector y satisfies A transpose y nonnegative and b transpose y negative. This is separation from the finitely generated cone of A's columns. To certify an optimum, check both feasibilities and equal objective values; matrix-vector checks suffice once the candidate pair is supplied.
Dual variables are local sensitivity bounds. While the same optimal basis remains valid, y i gives the change in optimal value per infinitesimal unit of resource i. A whole extra unit can leave that range. We add one unit and resolve: resource one's gain is one third, although its original dual price is one. Complementary slackness says a resource with positive slack has zero price, and a product with strictly positive reduced cost is unused. Resource two has slack one and price zero; product two has reduced cost three and quantity zero. These prices describe this mathematical model and its local range; they need not equal the finite change from any proposed large intervention.
4Exponential in theory, fast in practiceGraduate2 min
How many pivots can simplex need? Klee and Minty constructed deformed cubes showing exponential behavior for Dantzig's rule. We execute a fixed power-coefficient variant: each upper row depends on all earlier coordinates, with powers of two in the matrix and powers of five on the right. The objective also uses powers of two. This is the model drawn here after rescaling the axes. Exact arithmetic checks feasibility and strict objective increase at every visited vertex. Dantzig visits all two to the n vertices on these instances. In three dimensions that is seven pivots through eight corners, not a theorem about every pivot rule or every cube.
We ran our simplex on Klee–Minty cubes up to twelve dimensions. Dantzig's rule takes exactly two to the n minus one pivots, every time: four thousand and ninety-five at twelve. Bland's rule does better on this cube but is exponential on its own variants, as David Avis and Chvátal showed. The greatest-improvement rule, which tries every edge and takes the one that gains most, solves this cube in one pivot; Robert Jeroslow built cubes in 1973 that defeat it too. The pattern repeated for decades: almost every pivot rule proposed has acquired its own bad example, the last famous one, Zadeh's rule, in 2011. No pivot rule is known to run in polynomial time.
Finite experiments and smoothed analysis answer different questions. Our dense positive random LPs take relatively few Dantzig pivots on these one hundred seeded instances; their optimal values are checked independently. Spielman and Teng analyze a particular two-phase shadow-vertex method under additive Gaussian perturbations of constraint normals and right-hand sides. Their expected polynomial bound depends on dimensions and inverse perturbation scale. It is not a theorem for our Dantzig implementation. Our separate cube experiment multiplies nonzero matrix entries by one plus sigma times a Gaussian. Zeros stay zero. The table summarizes only optimal runs and separately counts unbounded ones; every status is checked against another solver. These observations illustrate sensitivity under this chosen model. They do not establish the shadow-vertex theorem, nor show that all bad instances disappear under arbitrary noise.
5Polynomial time: ellipsoids and the central pathGraduate2 min
Khachiyan's 1979 result gives polynomial bit complexity for rational linear programming. This illustration starts with a radius-six ball whose enclosure of the target region is checked separately. If its centre violates a constraint, that constraint gives a central separating cut containing the feasible region. Replace the retained half with an enclosing ellipsoid and repeat. In exact arithmetic its volume contracts by at least the displayed factor. A full complexity argument also needs input encoding and radius or lower-dimensional feasibility treatment; small volume alone does not prove an arbitrary region empty. Our floating run finds a feasible point after nine cuts. Exhausting its numerical cut budget would mean no point found, not a general infeasibility certificate.
How many cuts do these examples take? As this fixed two-dimensional region becomes thinner, the recorded counts rise. This finite table is not a fitted universal iteration law. Polynomial bit complexity for rational LP depends on dimension and coefficient encoding; exact-arithmetic work and floating iteration counts are different measurements. Ellipsoids are primarily a theoretical tool for LP rather than the usual production solver. Their lasting result is the separation-optimization equivalence for appropriately represented, bounded convex sets with the required radius and accuracy information. Exponentially many constraints can be handled when a polynomial-time separation oracle and these representation assumptions are available.
Karmarkar's 1984 breakthrough made interior-point methods central to practical optimization. This illustration is a log-barrier Newton path follower. Begin strictly inside all the inequalities. Minimize minus t times the objective minus the sum of log slacks. The negative logarithms repel the boundary. Under the usual existence and nondegeneracy conditions, central points approach an optimal face as t grows; this example has the unique optimum two, three. The ideal central point has duality gap m over t. Our approximate Newton points instead carry independently checked rational gap upper bounds, including stationarity residuals. The familiar square-root-m iteration theorem requires a specified short-step method and centrality control. Our one hundred twenty-seven Newton steps do not establish that theorem or a size-independent practical count. Strict feasibility, line-search convergence and the cost of linear solves all matter.
6When the vertices are integersGraduate3 min
Some integer models have integral linear relaxations. Give each edge of a bipartite graph a variable between zero and one, with incident values summing to at most one at each vertex. Its unsigned vertex-edge incidence matrix has two ones per column. Bipartiteness makes this matrix totally unimodular: every square minor is zero or plus or minus one. We independently check all nine hundred twenty-three nonempty square minors in the drawing. A partial minor search would be inconclusive. With integer right-hand sides and integer variable bounds, the augmented constraint matrix stays totally unimodular. Every nonsingular vertex basis has determinant plus or minus one, so Cramer's rule gives integer coordinates. Thus an optimal vertex solves the matching problem. All one hundred seeded weighted bipartite LPs have exact primal-dual certificates and agree with independent integer matching optima.
Outside bipartite graphs it fails, and the smallest failure is a triangle. Its incidence matrix has determinant two. The linear program happily puts one half on each edge, for a total of one and a half, though any matching in a triangle has just one edge. On a hundred random weighted graphs that were not bipartite, a quarter of the optimal vertices were fractional. Jack Edmonds repaired it in 1965: add a constraint for every odd set of vertices, saying it contains at most half as many edges, rounded down, and the polytope is integral again. There are exponentially many such constraints, but a violated one can be found quickly, so by chapter five's theorem the program is still solvable in polynomial time.
Integrality explains familiar combinatorial optimization results. A directed graph's node-arc incidence matrix is totally unimodular; adding integer capacity bounds preserves the flow integrality argument. LP duality then yields the max-flow min-cut relationship. Integral capacities admit an integral maximum flow, although fractional optimal flows may also exist as combinations of optimal vertices. Consecutive-ones interval matrices and network matrices provide other useful totally unimodular families. Seymour's decomposition of regular matroids, using graphic, cographic and the exceptional R-ten building block with specified sums, underlies polynomial recognition. Our brute-force minor enumeration is an exact small-matrix teaching check, not that recognition algorithm.
7Integer programmingIndustry4 min
Insist that the answer be made of whole things, and linear programming becomes NP-hard. The standard attack keeps linear programming as a guide. Here is a knapsack: eight items with values and weights, and a capacity of eighty. Relax it: let items be taken fractionally. That linear program is easy, greedy by value per unit of weight, and its optimum bounds what any whole choice can reach. The root's bound is a hundred and eighty-four, with one item taken in part. Branch on that item: one subproblem takes it, the other leaves it out, and each has its own bound. Any node whose bound cannot beat the best whole answer found so far is pruned without being explored. Here the best answer, a hundred and seventy-four, is found and proved optimal after twenty-four nodes, instead of the two hundred and fifty-six possible choices. Ailsa Land and Alison Doig invented the method in 1960, at the London School of Economics.
An exact bound matters even when a fraction looks like an integer. Both items are worth one hundred; their weights are a trillion and one, and capacity is a trillion minus one. The relaxation takes the light item and one minus two trillionths of the heavy item. Its value is just below two hundred. Rounding that fraction to one would select both items and exceed capacity by two. A small coordinate error has become an invalid solution. Exact branching rejects the heavy-item branch as infeasible and keeps the light item, proving an integer optimum of one hundred. Closeness to an integer cannot replace feasibility and exact branch logic.
How well does branch and bound scale here? On these forty random knapsacks up to one hundred sixty items, tight fractional upper bounds prune most of the search. Independent capacity dynamic programming checks every integer optimum; this finite family gives no worst-case speed guarantee. Gomory cuts add inequalities valid for whole solutions but violated by a fractional candidate. Branch and cut combines these ideas with presolving and heuristics. Progress in solvers depends on problem family, benchmark protocol, algorithms and hardware. We make no single universal speedup claim from this experiment. The resulting models support crew scheduling, energy systems, kidney exchanges and placement problems, subject to their own constraints and validation.
Knapsack also admits controlled approximation. Capacity dynamic programming is exact but pseudopolynomial: the numeric capacity may be exponential in its bit length. Our standard value-scaling teaching scheme first removes overweight items, then rounds feasible values down in units of epsilon times the largest feasible value divided by the item count. This is not the faster original Ibarra-Kim implementation. Total rounding loss is at most epsilon times that largest value, hence at most epsilon times OPT. The scaled sum is quadratic in n over epsilon; this code's reported n times that sum is a work model, not allocated table memory. The correlated twenty-item experiment checks each result against an independent exact optimum. High observed accuracy is welcome, but the promised guarantee remains one minus epsilon; the repeated host timings are observations, with generation and validation outside the clock.
8Approximation: coversDegree3 min
When the exact answer is out of reach, ask for an answer provably close to it. A vertex cover is a set of vertices touching every edge, and finding the smallest one is NP-hard. Here is a two-line algorithm. Take any edge whose ends are both uncovered and add both ends. Repeat until every edge is covered. The edges it took share no vertex, and any cover at all must contain at least one end of each of them, so the optimum is at least half of what we took. That is a factor two guarantee, proved without knowing the optimum. Here it takes eight vertices, against an optimum of six. The second way uses the linear program: give each vertex a fraction, require each edge's two fractions to sum to at least one, and minimize the total. Then keep every vertex whose fraction is at least a half. The relaxation's vertices only take the values zero, a half and one. Here it puts a half everywhere, four and a half in all, a lower bound on the optimum, and rounding keeps all nine. Again at most twice the linear program, so at most twice the optimum.
We checked both methods on a hundred seeded sixteen-vertex graphs against exhaustive optima. Their finite ratios stay within two. Tightness needs the right examples and the actual tie policy; it does not follow from this table. Khot and Regev show, assuming the Unique Games Conjecture, hardness for every fixed factor two minus epsilon. That is a conditional asymptotic statement, not a limit measured by our sample. On the complete graph the fractional cover value is n over two and the integer optimum n minus one. Their ratio approaches two as n grows. This relaxation therefore cannot certify a uniformly smaller factor on all graphs.
Set cover asks for the fewest sets covering every element. Greedy chooses a set covering the most currently uncovered elements. Our domain rejects families that cannot cover the universe. The classic guarantee is H n times optimum, with n the universe size. Charge each newly covered element an equal share of its chosen set's unit cost. Elements of any optimum set pay at most the harmonic sum, so all chosen costs total at most H n times OPT. The retained doubling-column examples have optimum two; their actual greedy choices and all sixty random instances are checked by an independent subset-union dynamic program. Selected hardness results have distinct premises: Feige's 1998 threshold uses a stronger complexity assumption, while Dinur and Steurer establish fixed-epsilon logarithmic NP-hardness. Observed small average gaps do not weaken these worst-case statements.
9The travelling salesmanGraduate3 min
The travelling salesman seeks a shortest tour. For general nonmetric distances, a fixed-factor polynomial approximation would decide Hamiltonian cycle, so no such guarantee exists unless P equals NP. Assume instead a complete symmetric metric with triangle inequality, as for these planar Euclidean points. An MST costs at most the optimum tour. Doubling its edges gives an Euler walk of cost at most twice OPT, and metric shortcuts give a tour. Christofides and Serdyukov improve this by matching the tree's odd-degree vertices. A minimum perfect matching costs at most half OPT; adding it makes every degree even, and shortcutting the Euler walk yields a tour. The factor is three halves for the specified metric model. Independent Kruskal and blossom calculations check our MST and matching weights. Held-Karp finds the combinatorial optimum using floating Euclidean lengths, separately checked by a backward recurrence. Our teaching matching uses exponential subset DP; it is not a polynomial blossom implementation.
These forty seeded twelve-city instances compare finite tour ratios with independently checked optima. Double tree and Christofides obey their metric guarantees. Nearest neighbour followed by two-opt has the smallest sample mean here. Two-opt tries improving pairs of edges; uncrossing is one kind of improvement, not its entire definition. That empirical outcome is specific to this family and stopping rule. The combined heuristic inherits nearest neighbour's logarithmic metric guarantee because it never lengthens the starting tour. A selected 2021 randomized metric-TSP theorem of Karlin, Klein and Oveis Gharan gives three halves minus a positive epsilon larger than ten to the minus thirty-six. It is a separate algorithm, not executed here, and is not presented as today's best bound. Euclidean TSP also admits a polynomial-time approximation scheme for each fixed positive epsilon, with dimension and epsilon dependence kept in its cost.
Implementation cost matters alongside guarantees. Held-Karp's exponential state count makes fifteen cities a small timing case, not a scalable route planner. The caption reports the minimum of three shared-host runs on identical prepared points. At three hundred cities we time two-opt alone, after nearest neighbour has prepared the starting tour. Generation, length checks and references run outside the clock. The zero point seven one two four square-root-n expression is a numerical asymptotic prediction for independent uniform points in the unit square. It is neither this instance's optimum nor a finite gap certificate. Lin-Kernighan and LKH use more powerful local moves, with performance depending on the instance and configuration. Concorde has proved optimality for a particular eighty-five-thousand-nine-hundred-city circuit-board instance using exact certification machinery. That historical result is not a runtime promise for arbitrary inputs. Delivery, drilling and scheduling often add constraints beyond symmetric metric TSP, so their models require separate checks.
10A random hyperplane: MAX-CUTGraduate3 min
A geometric relaxation gives a useful route to MAX-CUT. Split vertices into two sides and maximize crossing edges, an NP-hard problem. Encode each side by a sign, so an edge contributes one minus the sign product over two. Replace signs by unit vectors; their Gram matrix gives a semidefinite relaxation. We optimize vectors locally by projected gradient. That produces a feasible primal objective, not a certified global SDP optimum. The three-dimensional sphere is a separate rank-three visualization. For this graph the exact cut is eighteen. A separate rational dual matrix certificate bounds it above; local vector values and certified upper bounds are stored separately. A random plane through the origin rounds the pictured vectors to an actual feasible cut.
A two-vertex graph makes the certificate issue visible. Its one edge can certainly be cut. Start our seeded vector solver but allow zero gradient steps. Its feasible local objective is about zero point one three eight, below the exact cut value one. It therefore cannot be an upper bound. Independently choose both dual multipliers equal to one half. The displayed quadratic form is a square divided by four, so the dual matrix is positive semidefinite and the multipliers sum to one. That separate certificate proves every cut is at most one. A feasible cut attaining one and a valid dual upper bound of one close the gap; a local primal value alone would not.
Why does hyperplane rounding help? Vectors at angle theta are separated with probability theta over pi. Compare this probability with the edge's vector reward, one minus cosine theta over two. The ratio is at least alpha, about zero point eight seven eight. Its minimum is near one hundred thirty-four degrees, checked here by an independent scalar root solve. For any fixed vectors, expected cut is at least alpha times their own objective. To conclude alpha times the integer optimum, the theorem uses a globally optimal SDP solution, or explicitly accounts for its optimization error. Our local solver alone supplies neither premise. Independent random vertex labels give the elementary one-half guarantee. A finite average of sampled cuts estimates an expectation; it does not prove a universal bound.
These thirty seeded graphs have separately enumerated exact maximum cuts. The table compares two hundred valid random vertex assignments and two hundred hyperplanes per graph. It reports finite means and best observed cuts. Exact rational positive-definiteness certificates give separate dual upper bounds; the projected-gradient objectives remain local primal observations. The dated Khot-Kindler-Mossel-O'Donnell result says, under the Unique Games Conjecture, no polynomial algorithm uniformly improves alpha by a fixed positive amount. Without that conjecture, Håstad's hardness excludes a factor sixteen seventeenths plus any fixed epsilon unless P equals NP. Geometry and random rounding are the template; the certificate, optimization error and expectation model determine which guarantee actually follows.
11Online: deciding without the futureDegree3 min
Online decisions arrive before their future is known. Rent skis for one per day or buy for ten. The discrete convention charges rental only on days before purchase. Compare cost with the clairvoyant optimum, the smaller of season length and ten. For randomized rules the season must be fixed independently of the random buy day. Rent nine days, then buy: the worst ratio is nineteen over ten. A deterministic lower-bound adversary ends the season on the purchase day. This gives the required ratio even for a rule that buys early. For our buy-day distribution the exact discrete ratio is one over one minus nine tenths to the tenth power, about one point five three five. The familiar e over e minus one is the continuous or large-buy-price limit, about one point five eight two. The sampled curve estimates the separately calculated exact expectation.
We replay only the Job's data accesses, excluding instruction fetches. Its one hundred fifty-five thousand two hundred sixty-six accesses map to ninety-two distinct sixty-four-byte lines. The model is an initially empty fully associative cache with unit miss cost, not a hardware latency simulation. Belady evicts the page whose next use lies furthest ahead; offline next-use preprocessing is separate from online policy work. An independent full-trace simulator checks every displayed result. The table shows finite outcomes for these capacities and seeds, including least recently used, first in first out and random policies. Marking clears marks at a new phase and evicts a random unmarked resident. Its two-H-k expected competitive theorem assumes an oblivious request sequence and allows an additive initial term. These particular random outcomes establish no universal winner.
A cyclic trace exposes one weakness of least recently used. Cycle over five pages with capacity four: every request misses under LRU. Offline OPT misses roughly once per four requests after its initial fills; the exact finite counts appear here. This fixed cycle alone does not defeat every deterministic policy. The general lower bound uses an adaptive request to a page absent from that policy's cache. LRU and FIFO are k-competitive with the usual additive constant. Randomized marking's expected two-H-k upper bound concerns oblivious sequences, not that adaptive adversary. Locality, capacity, associativity and replacement cost determine which model helps explain a real cache. This unit-cost trace study isolates only one part of that behavior.
12Multiplicative weightsGraduate3 min
Multiplicative weights turns past losses into a distribution over experts. Each round our calculation assigns a probability to every expert before seeing that round's losses; it accumulates the distribution's expected loss, without sampling a realized expert. Multiply weights by the exponential of minus eta times loss, computed in stable log space. These seeded binary losses give one expert error probability forty-five percent and the rest fifty percent. Their finite histories are retained. Expected-loss regret compares the algorithm with the best fixed expert in hindsight. For losses in zero to one, the bound is log n over eta plus eta T over eight. Choosing eta for each displayed horizon gives the square root of T log n over two. Independent prefix-loss softmax calculations reproduce every row. A sampled expert's realized loss would additionally require a probabilistic deviation statement.
The proof is four lines, and it is worth seeing once. Watch the total weight. It starts at n, one per expert. At the end it is at least the weight of the best expert alone, which has been multiplied by e to the minus eta once for each of its losses. And in each round, when we follow an expert in proportion to the weights, the total weight shrinks by a factor of about e to the minus eta times our expected loss that round, with a small correction from Hoeffding's inequality. Chain the rounds together, and the two facts squeeze: our loss cannot be much more than the best expert's, or the weight would have fallen below the best expert's own. Take logarithms, choose eta to balance the two terms, and the regret is the square root of T over two times log n. It is a potential argument, like the amortized analyses of Parts 16 and 17, and the same pattern proves boosting and the minimax theorem.
The same update supplies finite game certificates. Let the maximizing row player use multiplicative weights and the column player choose a best response each round. Average the actual row and column distributions. The smallest payoff against the averaged row is a lower bound on the game value; the largest against the averaged column is an upper bound. Both distributions are retained and checked. A separate exact rational equilibrium certifies this game's value near zero point four eight four six. Finite gaps are not exact convergence. Related weighting ideas power boosting, with its own assumptions and update rules. Constraint weights also support approximate packing and flow solvers with explicit width and accuracy parameters. Arora, Hazan and Kale survey this shared potential-method pattern and its applications.
13Convex optimization in a pageGraduate2 min
This small convex example lets us compare actual optimization paths. The function is a two-dimensional log-sum-exp with the displayed coefficients. Its independent analytic optimum is minus half log two, zero. This instance is only moderately conditioned near that point. Gradient descent chooses step lengths by backtracking. Here it needs forty steps to make objective error less than ten to the minus ten, measured against the analytic value rather than Newton's last iterate. Newton solves the local Hessian system to obtain a step. Here it needs four steps. Quadratic local convergence requires regularity and a sufficiently close starting region; four observations do not prove a general digits-doubling law. A Newton step costs a linear solve. Structure, sparsity and dimension decide whether that cost is worthwhile; there is no universal winner.
Convexity gives powerful guarantees with explicit premises. Every local minimum of a convex objective on a convex domain is global, but existence of a dual certificate needs appropriate duality conditions. For differentiable convex inequalities, KKT includes primal feasibility, nonnegative multipliers, stationarity and complementary slackness. Slater's condition is one sufficient regularity condition for necessity and strong duality. The multipliers generalize LP shadow prices. LP, convex quadratic, second-order cone and semidefinite formulations offer increasingly expressive structured models. Polynomial complexity claims must specify input representation, an available barrier or oracle, accuracy and conditioning. Arbitrary convex functions do not automatically admit a uniform polynomial algorithm. General nonconvex optimization can be NP-hard; individual nonconvex problems can still be easy. Rockafellar's convex versus nonconvex watershed is a useful organizing principle, with these assumptions kept visible.
14Frontier: faster LPs, the Hirsch question, the UGCResearch4 min
The first frontier is complexity under a stated input model. Interior-point advances reduce both iteration count and the cost of maintaining successive linear systems. Arithmetic-operation bounds and bit complexity are different. The selected 2019 Cohen-Lee-Song result gives a dense-LP bound involving n to omega, two additional exponent terms, and a log accuracy factor. At the paper's exponent estimates the matrix-multiplication term dominates. Van den Brand gives a related deterministic bound. These dated theorems do not make every LP inherently equivalent to one matrix product. The selected 2022 six-author flow result gives almost-linear exact directed max-flow and min-cost flow for polynomially bounded integral input data. Dynamic graph and interior-point machinery are central to that result. The input assumptions and hidden factors belong to the theorem; none of these asymptotic algorithms is executed by our small Python examples.
The second frontier concerns paths along polytope edges. Our drawn bounded three-dimensional polytope has twenty-four facets, forty-four vertices and diameter eight. Independent breadth-first searches check every vertex's eccentricity. Hirsch conjectured diameter at most facets minus dimension. Each displayed row contains twenty seeded, certified bounded three-dimensional samples. We reject uncertified draws before construction; these finite means support no universal growth law or high-dimensional claim. Santos disproved the original conjecture with a forty-three-dimensional example having eighty-six facets and diameter at least forty-four. Kalai and Kleitman's 1992 quasipolynomial bound is historical, not the latest bound. Todd's 2014 refinement is at most n minus d to the power log base two d. A polynomial general diameter bound would be necessary but not sufficient for an efficient pivot rule: the rule must also find appropriate objective-improving paths. Our exercise compares finite routing rules without attempting to settle the open conjecture.
The third frontier asks how close polynomial algorithms can get. The table distinguishes selected algorithmic guarantees, unconditional NP-hardness thresholds and conditional Unique Games thresholds; fixed epsilon qualifications matter. The PCP theorem gives polynomial-size encodings of NP witnesses with a randomized verifier using logarithmically many random bits and constantly many queries. Completeness and a fixed soundness gap concern valid versus false statements, not perfect error detection in arbitrary proofs. Gap reductions yield approximation hardness, including Håstad's seven-eighths-plus-epsilon barrier for MAX-3SAT unless P equals NP. Under the Unique Games Conjecture the corresponding fixed-factor thresholds for vertex cover and MAX-CUT match their standard approximation guarantees. The two-to-two theorem yields a separate vertex-cover hardness result. Raghavendra's conditional optimality theorem concerns each fixed finite-domain constraint-satisfaction problem and its appropriate SDP rounding framework, not every problem called constraint satisfaction with unrestricted representation.
Three questions organize this frontier. Strongly polynomial LP asks for an arithmetic-operation count polynomial in dimensions and independent of coefficient bit lengths, while also controlling intermediate encoding size. This is not a claim that reading arbitrary-precision input is free. A general polynomial bound on polytope diameter remains a separate geometric question. The Unique Games Conjecture governs conditional approximation thresholds. Our research-style exercise stays finite: generate certified bounded polytopes, compute exact graph distances, and compare a specified routing rule with shortest paths. Report seeds, failures and model limits; a successful finite experiment does not settle any of these open questions.
Recap, problems, and where this comes backAll tracks3 min
What we built: linear programs with exact primal-dual certificates; a feasible-basis simplex whose budget status is explicit; and Klee-Minty instances checked in exact arithmetic. A separate shadow-vertex theorem explains one specified perturbation model. Ellipsoids, residual-certified barrier points and total unimodularity show where polynomial methods and integrality apply. Exact knapsack bounds expose why a nearly integral relaxation still needs a valid branch. Covers, metric tours and hyperplane rounding distinguish general guarantees from finite local measurements. Discrete ski rental, unit-cost paging and multiplicative weights keep their adversary and expected-loss models explicit.
Where this comes back. Part 27 builds the PCP theorem behind this part's hardness results, and the unique games conjecture. Part 32's kernel replaces pages with CLOCK, a cheap approximation of least recently used. Part 45's cloud packs virtual machines onto servers, an integer program solved by heuristics every second, and Part 48 balances load online. Part 52 explains why linear programming solvers fight floating point. And Part 57 turns multiplicative weights into a theory of learning. The AI series used this part's tools throughout: gradient descent and Newton's method, boosting, and the convex losses that make training tractable.
In practice. HiGHS, Gurobi, CPLEX and OR-Tools run simplex, barrier and branch and cut on problems with millions of variables. Airlines schedule crews, carriers route vehicles, and supply chains plan with integer programs. Power grids and kidney exchanges are cleared by optimization, with dual prices. Every cache makes online decisions, and every model is trained by the descendants of gradient descent.
Six exercises in the notes have worked guidance. The fifth designs a bounded three-by-three rational simplex port in Pebble; prove intermediate word bounds and verify it on the emulator before claiming a working build. The last is a finite reproducible study of certified bounded polytopes and routing rules, with independent breadth-first-search references. Its deliverable is measured evidence and explicit limits, not a solution to the polynomial Hirsch conjecture.
Next time, algorithms in practice. Big-O hides constants, and in production the constants and the machine decide. The everyday tools of real code: prefix sums, Fenwick and segment trees, two pointers, monotonic stacks and bit tricks. Then algorithm engineering, where a textbook hash table or binary search becomes many times faster by respecting the caches, branch predictors and vector units of Act Two, and how to measure that honestly. Part 24, Algorithms in Practice.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Part 27 builds the PCP theorem behind the hardness results and states the Unique Games Conjecture; Part 32's kernel replaces pages with CLOCK; Part 45 packs virtual machines, an integer program solved by heuristics, and Part 48 balances load online; Part 52 explains why LP solvers fight floating point; Part 57 turns multiplicative weights into a theory of learning.
Key results
The part's results in one place, for revision.
Try it
Lab 23 · A certificate, an exponential walk, and three guarantees
Run the simplex method on Chvatal's three-product LP in exact arithmetic and check its dual prices as a proof of optimality; count Dantzig's pivots on Klee-Minty cubes against 2^n - 1; then measure a factor-2 vertex cover against the exact optimum and the regret of multiplicative weights against its bound.
python -m videos.cs.labs 23
needs numpy, scipy, matplotlib · download lab23.py ·
source on GitHubthree-product LP x = (2, 0, 1), profit 13 after 2 pivots
dual prices y = (1, 0, 1): 5 y1 + 11 y2 + 8 y3 = 13, so no plan earns more
Klee-Minty cube, n = 10 Dantzig 1,023 pivots (2^10 - 1 = 1,023) Bland 177 greatest improvement 1
30 random LPs, 10 x 10 Dantzig pivots: mean 4.5, most 9
vertex cover by matching, 25 graphs mean ratio 1.63, worst 2.00 (guarantee 2)
Hedge, 10 experts, T = 5,000 regret 46.4 (bound sqrt(T ln n / 2) = 75.9)
Goemans-Williamson constant min of (theta/pi) / ((1 - cos theta)/2) = 0.8786 at 133.6 degrees
A dual solution turns an answer into a proof; the simplex walk can be exponentially long on a crafted cube and short on random data; and a guarantee (2, sqrt(T ln n / 2), 0.878) is a bound that measurements sit inside, usually with room to spare.
The code (109 lines; it asserts its own result)
"""Lab 23: solve an LP with its dual certificate, walk the Klee-Minty cube, and measure three guarantees."""
from videos.coursekit import labs # noqa: I001 (must stay first: it lets explainer.cs import without manim)
import math
import random
import numpy as np
from explainer.cs.algo import optim as op
TITLE = "A certificate, an exponential walk, and three guarantees"
GOAL = ("Run the simplex method on Chvatal's three-product LP in exact arithmetic and check its dual prices as a "
"proof of optimality; count Dantzig's pivots on Klee-Minty cubes against 2^n - 1; then measure a factor-2 "
"vertex cover against the exact optimum and the regret of multiplicative weights against its bound.")
TASKS = [
"Add one unit of the first resource (b = [6, 11, 8]) and solve again. The profit rises by 1/3, not by the dual price 1: which basis changed?",
"Run the Klee-Minty cubes with rule='bland' up to n = 10 and fit the growth of its pivot count. Is it polynomial on this family?",
"Halve and double eta in the Hedge experiment and plot the regret: which side of the tuned value hurts more, and which term of the bound explains it?",
]
C3, A3, B3 = [5, 4, 3], [[2, 3, 1], [4, 1, 2], [3, 4, 2]], [5, 11, 8]
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. Chvatal's LP: the optimum and the proof that it is one
r = op.simplex(C3, A3, B3, exact=True)
x, y = r["x_exact"], r["duals_exact"]
assert r["status"] == "optimal" and x == [2, 0, 1] and r["value_exact"] == 13 and r["pivots"] == 2
assert all(sum(a * v for a, v in zip(row, x)) <= b for row, b in zip(A3, B3)), "x is feasible"
assert all(v >= 0 for v in y) and all(sum(A3[i][j] * y[i] for i in range(3)) >= C3[j] for j in range(3)), "y is dual feasible"
assert sum(b * v for b, v in zip(B3, y)) == sum(c * v for c, v in zip(C3, x)) == 13, "equal objectives: both optimal"
slack = [b - sum(a * v for a, v in zip(row, x)) for row, b in zip(A3, B3)]
assert all(s * v == 0 for s, v in zip(slack, y)), "complementary slackness"
lab.row("three-product LP", f"x = {tuple(int(v) for v in x)}, profit {r['value_exact']} after {r['pivots']} pivots")
lab.row("dual prices", f"y = {tuple(int(v) for v in y)}: 5 y1 + 11 y2 + 8 y3 = 13, so no plan earns more")
# 2. Klee-Minty: 2^n - 1 pivots for Dantzig's rule, one for greatest improvement
dims = list(range(2, 11))
pivots = {rule: [op.simplex(*op.klee_minty(n), rule=rule, exact=True)["pivots"] for n in dims]
for rule in ("dantzig", "bland", "steepest")}
assert pivots["dantzig"] == [2 ** n - 1 for n in dims], "Dantzig's rule visits every vertex"
assert pivots["steepest"] == [1] * len(dims), "greatest improvement takes one pivot on this cube"
values = {rule: op.simplex(*op.klee_minty(8), rule=rule, exact=True)["value_exact"] for rule in pivots}
assert len(set(values.values())) == 1 and values["dantzig"] == 5 ** 8, "every rule reaches the same optimum"
lab.row("Klee-Minty cube, n = 10", f"Dantzig {pivots['dantzig'][-1]:,} pivots (2^10 - 1 = 1,023) Bland {pivots['bland'][-1]}"
f" greatest improvement {pivots['steepest'][-1]}")
# 3. random dense LPs: few pivots, and the same value as an independent solver
from scipy.optimize import linprog
counts = []
lp_rng = random.Random(seed)
for _ in range(30):
c, A, b = op.random_lp(10, 10, lp_rng)
s = op.simplex(c, A, b)
ref = linprog([-v for v in c], A_ub=A, b_ub=b, bounds=[(0, None)] * 10, method="highs")
assert s["status"] == "optimal" and abs(s["value"] + ref.fun) < 1e-6 * max(1, abs(ref.fun)), "agrees with HiGHS"
counts.append(s["pivots"])
assert max(counts) < 100, "nowhere near the 2^10 - 1 of the cube"
lab.row("30 random LPs, 10 x 10", f"Dantzig pivots: mean {np.mean(counts):.1f}, most {max(counts)}")
# 4. vertex cover: both ends of a maximal matching, against the exact optimum
ratios = []
for g in range(25):
nv = 12
edges = [(i, j) for i in range(nv) for j in range(i + 1, nv) if rng.random() < 0.3]
opt = op.vertex_cover_exact(nv, edges)[0]
cover = op.vertex_cover_matching(nv, edges, seed=g)
assert all(u in cover or v in cover for u, v in edges) and len(cover) <= 2 * opt, "a cover within factor 2"
if opt:
ratios.append(len(cover) / opt)
assert max(ratios) > 1, "and not always optimal"
lab.row("vertex cover by matching, 25 graphs", f"mean ratio {np.mean(ratios):.2f}, worst {max(ratios):.2f} (guarantee 2)")
# 5. multiplicative weights: regret at most sqrt(T ln n / 2)
n_exp, horizons, regrets = 10, [50, 100, 200, 500, 1000, 2000, 5000], []
p = np.full(n_exp, 0.5)
p[0] = 0.45 # one expert is slightly better, as in the film
losses = (rng.random((horizons[-1], n_exp)) < p).astype(float)
for T in horizons:
alg, best, _ = op.hedge(losses[:T], math.sqrt(8 * math.log(n_exp) / T))
regrets.append(alg - best)
assert alg - best <= math.sqrt(T * math.log(n_exp) / 2) + 1e-9, "the regret bound holds at every horizon"
assert regrets[-1] / horizons[-1] < 0.02, "average regret tends to zero"
alpha, angle = op.gw_alpha()
assert abs(alpha - 0.8786) < 1e-3 and abs(math.degrees(angle) - 133.56) < 0.5
lab.row("Hedge, 10 experts, T = 5,000", f"regret {regrets[-1]:.1f} (bound sqrt(T ln n / 2) = {math.sqrt(5000 * math.log(10) / 2):.1f})")
lab.row("Goemans-Williamson constant", f"min of (theta/pi) / ((1 - cos theta)/2) = {alpha:.4f} at {math.degrees(angle):.1f} degrees")
lab.note = ("A dual solution turns an answer into a proof; the simplex walk can be exponentially long on a "
"crafted cube and short on random data; and a guarantee (2, sqrt(T ln n / 2), 0.878) is a bound that "
"measurements sit inside, usually with room to spare.")
fig, ax = labs.figure(2, size=(11, 4.4))
for rule, color, name in (("dantzig", labs.RED, "Dantzig: 2ⁿ − 1"), ("bland", labs.GOLD, "Bland"),
("steepest", labs.GREEN, "greatest improvement")):
ax[0].semilogy(dims, pivots[rule], "o-", color=color, label=name)
ax[0].axhline(np.mean(counts), color=labs.BLUE, ls="--", label="random 10 × 10 LPs, mean")
ax[0].set(title="Simplex pivots on Klee-Minty cubes", xlabel="dimension n", ylabel="pivots")
ax[0].legend()
ax[1].loglog(horizons, regrets, "o-", color=labs.BLUE, label="Hedge: regret against the best expert")
ax[1].loglog(horizons, [math.sqrt(T * math.log(n_exp) / 2) for T in horizons], color=labs.GOLD, label="bound √(T ln n / 2)")
ax[1].loglog(horizons, [0.02 * T for T in horizons], color=labs.MUTED, ls="--", label="linear regret, for scale")
ax[1].set(title="Multiplicative weights, 10 experts", xlabel="rounds T", ylabel="expected-loss regret")
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Add one unit of the first resource (b = [6, 11, 8]) and solve again. The profit rises by 1/3, not by the dual price 1: which basis changed?
- Run the Klee-Minty cubes with rule='bland' up to n = 10 and fit the growth of its pivot count. Is it polynomial on this family?
- Halve and double eta in the Hedge experiment and plot the regret: which side of the tuned value hurts more, and which term of the bound explains it?
Problems, with solutions
Try each problem before opening its solution.
Six exercises, with worked solutions
-
Duality. Prove weak duality and complementary slackness for
max c^T x : Ax<=b, x>=0andmin b^T y : A^T y>=c, y>=0.Solution
For feasible x,y,
c^T x <= y^T Ax <= y^T b. At an attained equal optimal pair, both inequalities are equalities. Thereforey^T(b-Ax)=0andx^T(A^T y-c)=0. Each summand is nonnegative, so each product vanishes. The chapter's primal(2,0,1)and dual(1,0,1)both give 13; primal slack(0,1,0)and reduced costs(0,3,0)satisfy these products. Check feasibility before interpreting an equal objective as a certificate. -
Half-integrality. Show every vertex of the unbounded vertex-cover LP
{x>=0 : x_u+x_v>=1}lies in{0,1/2,1}^V.Solution
If
x_v>1, every edge incident to v has positive slack. Perturb x_v both ways by a sufficiently small amount; feasibility persists, so x is not a vertex. Thus every vertex already lies in the unit box; merely showing a box optimum exists would not prove the statement. LetV+={v:1/2<x_v<1}andV-={v:0<x_v<1/2}. If either is nonempty, perturb by±epsilon(1_V+ - 1_V-). Every tight edge either joins 0 to 1, joins two halves, or joins V+ to V-, in which case changes cancel. Finitely many slack edges remain feasible for sufficiently small epsilon. This expresses x as a midpoint of distinct feasible points, a contradiction. -
Ski rental. Prove the discrete deterministic optimum ratio
2-1/B.Solution
Renting
B-1days then buying costs d whend<B, and2B-1otherwise. A deterministic rule buys on a fixed day k if the season persists. End the season on day k: costk-1+Bversusmin(k,B). Fork<=B, ratio is1+(B-1)/k >= 2-1/B; fork>Bit is at least 2. Never buying has unbounded ratio. At B=1 the optimal action is immediate purchase, with ratio 1. This deterministic adversary must not be reused after observing a randomized buy day when claiming the oblivious-season randomized theorem. -
Hyperplane constant. Minimize
r(theta)=theta/(1-cos(theta))on(0,pi].Solution
Its derivative has numerator
1-cos(theta)-theta*sin(theta). An interior stationary point obeystan(theta/2)=theta. The derivative is negative near zero and positive near pi. The functiontan(theta/2)-thetadecreases then increases (its derivative crosses zero once), giving a unique positive root near 2.3311. Compare the endpoint and the limit at zero to obtain the minimum. Thenalpha=2*r(theta)/pi≈0.8786. This scalar calculation proves the edgewise inequality, not global convergence of the local vector solver. -
Build: a bounded Pebble port. Implement Bland simplex for only the fixed 3×3 integer LP in chapter one, using reduced signed numerator/positive denominator pairs. Verify status, objective 13 and both feasibilities on the emulator before claiming the port works. Arbitrary matrices are outside scope.
Solution
Guidance: append the identity slacks and b; initialize the objective row to
(-5,-4,-3,0,0,0,0). Bland bases are(3,4,5),(0,4,5),(0,4,2)using zero-based columns. The two pivots have values 2 and 1/2; the last objective row is(0,3,0,1,0,1,13). Implement gcd normalization after every fraction operation, a positive denominator, signed comparisons by cross-products, minimum-index entering choice and Bland ratio ties. Report iteration limit separately, and reject input outside this fixed contract.Word proof for this path: inspect the initial, normalized-pivot and updated tableaux; stored reduced numerators have magnitude at most 25 and denominators at most 2. A multiply-then-subtract update has intermediate numerator bounded by
25^2*2+25*2^2=1350and denominator at most2^3=8. A ratio comparison has cross-product magnitude at most(25*2)^2=2500. Division numerators and denominators are at most 50. Thus all these integer intermediates are below2^12, safely within Pebble's signed 32-bit words for this specified trace. This is a bounded design and reference trace, not a completed emulator run. -
Research-style finite study. Generate bounded 3D polytopes from unit normals, certify boundedness before construction, and compare a fixed routing rule with independently computed shortest paths. Do not infer a general Hirsch result from random samples.
Solution
Worked method: require four affinely independent normals with strictly positive rational barycentric weights summing to one and weighted sum zero. Their convex hull contains a neighbourhood of zero, so their inequalities bound every direction. Record rejected draws rather than treating solver failure as proof of unboundedness. Construct vertices numerically, record tolerances, check active facets, connectivity and Euler's relation, then run independent BFS from every vertex. Specify the routing rule before inspecting results; include trapped paths, ties and iteration limits in the report. Preserve normals, vertices, graph, seeds and path certificates. A polynomial graph diameter bound would still not by itself give an efficient improving simplex pivot rule.
Notes and sources
About this partfrom its README
Part 23 of the 61-part series, in Act IV, Algorithms. Optimization needs a model, a feasible answer and the right certificate. This part builds exact small examples alongside numerical experiments and separates their claims from selected dated research results.
The instrument is explainer/cs/algo/optim.py; its 27 tests are in
tests/test_cs23_optim.py. Fifteen producers in compute.py retain full measured
instances, independent references and certificates. Schema-2 cache entries bind
the actual producer, instrument and reference-module hashes. Changing any of
those sources invalidates the cache. Repeated algorithm timings exclude input
generation, hashing and independent validation; producer wall time includes them
and is not an algorithm benchmark. Shared-host times are observations.
What is computed and built
- LP and simplex. The bounded three-product polytope has six independently
enumerated rational vertices. The optimum
(2,0,1)has value 13 and dual(1,0,1). Transportation shipments and a signed supply/demand dual both give 365; ignoring plant capacity gives an infeasible 355 allocation. A general LP feasible set is a polyhedron and need not be bounded. This full-tableau simplex requires a feasible slack basis (b >= 0), with no Phase I. Each pivot usesO(m(n+m))arithmetic; the selector calledsteepesttries greatest total improvement, rather than normalized steepest edge. Independent basis solves reconstruct every displayed tableau. A zero-budget witness returns a feasible incumbent withiteration_limit; one permitted pivot gives matching primal and dual certificates. Degeneracy can require zero-length pivots. - Duality. Weak duality applies to feasible primal/dual pairs. Feasible LPs with a finite optimum have attained equal dual optima. Farkas' alternatives use the stated signs. Shadow prices are local sensitivities within a valid basis range; adding a whole unit of resource one raises profit by 1/3 despite its original dual price 1. Exact complementary slackness is checked.
- Klee–Minty. The executed zero-based variant has
c_j=2^(n-1-j), diagonal coefficients 1, earlier coefficients2^(j-i+1), andb_j=5^(j+1). All 33 rule/dimension runs from 2 through 12 use exact arithmetic. Dantzig takes2^n-1pivots, with every visited point checked for feasibility, distinctness and strict objective increase. Greatest improvement is a different rule. Every one of 101 multiplicatively perturbed cubes and 100 positive dense LPs has an independent solver reference; statuses and full data are retained. This zero-preserving multiplicative Dantzig experiment is separate from Spielman–Teng's additive-Gaussian, two-phase shadow-vertex theorem. - Ellipsoid and barrier. Eight finite 2D regions have exact boundedness and
radius-six enclosure checks. Floating returned centres and determinant area
ratios are numerical observations; exhausting the cut budget is not a general
infeasibility certificate. A log-barrier path uses strict interiors and checked
Newton/line-search convergence. All 36 approximate points have exact rational,
residual-corrected objective upper bounds over a proven box. The ideal central
gap
m/tis retained separately. The short-step iteration theorem requires its own centrality assumptions and is not a guarantee for this schedule. - Integrality. Exact Bareiss determinants agree with independent Leibniz/GMP references. All 923 square minors of the small bipartite incidence matrix and 19 of the triangle are checked. Partial minor searches return inconclusive. Integer right-hand sides and bounds are essential to TU integrality. All 201 illustrated/measured matching LPs have exact primal/dual certificates; all 100 bipartite values also agree with an independent integer matching solver. Fractional optimal vertices occur in 0 bipartite and 25 general samples. Seymour's regular-matroid decomposition is separate from exhaustive minors.
- Knapsack. Exact fraction ratios and bounds avoid binary64 integer ties and
nearly integral overweight answers. The eight-item example has optimum 174,
root bound
6437/35, and 24 processed nodes. All 41 integer optima agree with independent arbitrary-precision capacity DP. An executed two-item witness has weights(10^12,1), capacity10^12-1, relaxation value200-2/10^10, and integer optimum 100; rounding its heavy fraction to one exceeds capacity by 2. The value-scaling teaching FPTAS removes overweight items before scaling and checks each guarantee exactly. Its reportednVis a work model, not allocated table memory; it is not the faster original Ibarra–Kim implementation. - Covers. All 101 vertex-cover optima agree with vectorized exhaustive masks; exact half-integral cover/fractional-matching dual certificates check the LPs. Feasible maximal-matching and rounded covers satisfy their factors. All 66 set-cover optima agree with a separate subset-union DP, with full families and chosen sets retained. Empty and uncoverable domains are handled explicitly. Finite mean ratios and tie policies do not establish worst-case tightness.
- Metric TSP. Complete symmetric metric assumptions support double tree's 2
and Christofides–Serdyukov's 3/2 guarantees. All 42 small optima agree with a
backward subset recurrence using floating Euclidean lengths. Forty-one full
approximation cases also check tours, Kruskal MST and blossom matching weights.
The teaching perfect matching itself uses exponential subset DP. Nearest-neighbour plus 2-opt inherits the logarithmic metric guarantee because
it never lengthens the starting tour. Large 2-opt timings and sample means are
finite observations.
0.7124 sqrt(n)is a numerical asymptotic prediction for independent uniform planar points, not an optimum or gap certificate for one instance. General nonmetric hardness assumesP != NP. - MAX-CUT. All 31 exact graph optima have independent exhaustive references.
Random cuts assign one side to each vertex, not independently to each edge.
Rank-three pictured vectors and other locally optimized vector objectives are
separate from exact rational dual upper bounds. Positive rational LDL pivots
certify
Diag(lambda)-L/4positive definite in the measured cases. A one-edge witness has local value about 0.138 below OPT 1, while the independent duallambda=(1/2,1/2)has a positive-semidefinite square-form certificate and upper bound 1. Hyperplane expectation is at leastalpha F(V)for fixed vectors;alpha OPTrequires an optimal SDP or an explicit optimization-error allowance. Finite sample means do not prove the universal theorem. - Online models. Discrete ski rental charges before the purchase day. At
B=10the exact randomized competitive ratio is1/(1-(9/10)^10) = 1.5353399328;e/(e-1)is the continuous/large-B limit. The season is fixed independently of the random buy day. Paging replays all 155,266 Job data accesses, excluding instruction fetches, on 92 distinct 64-byte lines in an initially empty, fully associative, unit-miss model. Every full-trace policy result and cyclic example has a separate list/future-queue reference. Offline next-use preprocessing is separate from online work. Marking's expected2H_ktheorem uses oblivious requests and an additive initial term. A fixed cycle defeats LRU, not every deterministic policy; the general deterministic lower bound uses policy-adaptive requests. - Multiplicative weights. Stable log weights accumulate expected loss for
losses in
[0,1]. Every horizon retunes eta and agrees with an independent vectorized prefix-loss softmax calculation. Hoeffding givesln(n)/eta + eta*T/8; chosen eta yieldssqrt(T*ln(n)/2). A sampled expert's realized regret needs a separate deviation statement. Every finite game row retains actual averaged row/column strategies and valid lower/upper bounds; a separate rational equilibrium certifies value63/130. Finite gaps do not claim exact convergence. - Convex and frontier. Stable log-sum-exp uses the analytic minimizer
(-log(2)/2,0)and valuelog(2 sqrt(2))-.1, rather than Newton's last iterate as truth. The 40-versus-4 iteration result is specific to this moderately conditioned example and stopping threshold. Differentiable convex KKT includes primal feasibility; Slater is a sufficient regularity condition. Complexity requires representation, barrier/oracle, conditioning and accuracy assumptions. All 100 random bounded 3D polytopes plus the drawn example have exact positive normal certificates, numerical vertex/facet checks, Euler checks and independent all-source BFS diameters. Rejected draws are retained. These samples do not establish a diameter growth law or a high-dimensional Hirsch claim.
Selected research is dated and scoped: Spielman–Teng's actual perturbation model; Cohen–Lee–Song (2019), whose full bound includes additional exponent and accuracy terms; van den Brand's related deterministic bound; Chen et al. (2022) for exact flow with polynomially bounded integral data; Karlin–Klein–Oveis Gharan (2021), whose randomized metric-TSP algorithm is not run here; and Todd (2014), refining the historical Kalai–Kleitman bound. PCP means an NP-witness encoding with completeness/soundness and constant queries. Raghavendra's UGC-conditional theorem concerns each fixed finite-domain CSP and its appropriate SDP rounding framework. None of these citations is presented as a current-best survey.
Primary sources for the selected research checks: Spielman–Teng, Cohen–Lee–Song, van den Brand, Chen et al., Karlin–Klein–Oveis Gharan, and Todd.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: Stigler's diet ($39.93 by insight, 1945); Laderman's simplex by hand ($39.69 and a proof, about 120 person-days); the three kinds of answer (proved, provably close, competitive).
- Linear programs: Chvátal's three-product LP; Kantorovich (1939), Dantzig (1947); modelling a transportation problem (Hitchcock 1941; $355 infeasible, $365 optimal) and the standard tricks; the feasible region as a 3D polytope with 6 vertices and the objective plane pushed to (2, 0, 1).
- Simplex: the walk 0 → 12.5 → 13 in 2 pivots, drawn in 3D and as tableaux (ratio test, elimination); degeneracy, cycling and Bland's rule; steepest edge and LU updates.
- Duality: the family of bounds (15, 13⅓, an infeasible one, 13); weak and strong duality, Farkas' lemma and a separating hyperplane; shadow prices measured (⅓ against y₁ = 1); complementary slackness.
- The Klee–Minty cube walked through all 8 vertices; 2ⁿ − 1 Dantzig pivots to n = 12, Bland 465, greatest improvement 1 (Jeroslow, Avis–Chvátal, Zadeh); smoothed analysis (Spielman & Teng 2001): random LPs and perturbed cubes (1,023 → 397 → 76 pivots).
- Polynomial time: Khachiyan's ellipsoid (9 cuts; steps against width); separation ≡ optimization (Grötschel, Lovász & Schrijver); Karmarkar's interior point, the log barrier and the central path (127 Newton steps).
- Total unimodularity: bipartite incidence matrices checked, Cramer's rule, 0 of 100 fractional; the triangle (det 2, all halves), 25 of 100; Edmonds' odd sets; max-flow/min-cut as duality (Part 18); Seymour.
- Integer programming: knapsack branch and bound (24 nodes of 256; a few hundred at n = 160, LP gap 0.06%); Gomory cuts; Bixby's speedups; the FPTAS by rounding (Ibarra & Kim).
- Approximation: vertex cover 2 by matching and by half-integral LP rounding, measured; Khot–Regev; greedy set cover H_n (proved), the harmonic trap, Feige.
- TSP: no factor in general; double tree, Christofides–Serdyukov; forty instances against Held–Karp (2-opt best at 1.013); Karlin–Klein–Oveis Gharan, Arora/Mitchell; 300 cities and BHH; LKH and Concorde.
- Goemans–Williamson: vectors on a sphere and a random hyperplane; θ/π against (1 − cos θ)/2, α = 0.8786 at 134°; thirty graphs against exact MAX-CUT; KKMO and Håstad.
- Online: ski rental (2 − 1/B; e/(e − 1) randomized); paging on the Job's trace (LRU 1.2–6.9× Belady; random and marking win at large k); the cyclic adversary and Sleator–Tarjan.
- Multiplicative weights: regret against √((T ln n)/2), measured; the potential proof; a zero-sum game converging to its LP value; boosting (AI, Built 6) and approximate LP (Arora, Hazan & Kale).
- Convex optimization in a page: gradient descent (40 steps) against Newton (4) on a stretched log-sum-exp; KKT; the LP ⊂ QP ⊂ SOCP ⊂ SDP ladder; Rockafellar's watershed (callbacks to AI, Built 4 and 11).
- Frontier: LP in matrix-multiplication time (Cohen, Lee & Song; van den Brand) and almost-linear max flow (Chen et al. 2022); the Hirsch conjecture, a drawn random polytope and random diameters against n − 3, Santos, Kalai–Kleitman; hardness of approximation (PCP, Håstad, the UGC, the 2-to-2 theorem, Raghavendra); open problems (strongly polynomial LP, polynomial Hirsch, the UGC). Outro.
Computed: every number above, in videos/cs/cs23/compute.py with explainer/cs/algo/optim.py (tested in
tests/test_cs23_optim.py): the simplex under three rules, exact and floating, against HiGHS; the transportation
optimum; duals, shadow prices and slacks; Klee–Minty, perturbed and random pivot counts; ellipsoid runs; the central
path; total unimodularity by brute force; branch and bound, DP and the FPTAS; vertex and set cover against brute
force; Held–Karp and the TSP heuristics; Goemans–Williamson by a Burer–Monteiro SDP against exact MAX-CUT; ski rental
and paging on the Job's trace; Hedge regret and a zero-sum game; gradient descent and Newton; random 3D polytope
diameters.
Visuals: the polytope with the objective plane and the simplex walk; tableaux pivoting; the dual's family of bounds
and a separating hyperplane; the squashed Klee–Minty cube; ellipsoids shrinking; the central path; the
branch-and-bound tree; covers on a graph; tours being built; a hyperplane slicing a sphere of unit vectors; the α
curve; expert weights converging; zigzagging gradient descent against Newton; a random polytope's longest path.
In practice: operations research (logistics, crew scheduling, ad allocation), LP and MIP solvers (Gurobi, HiGHS,
OR-Tools), cache replacement as an online problem.
Reading: Bertsimas & Tsitsiklis, Introduction to Linear Optimization; Chvátal, Linear Programming; Matoušek &
Gärtner, Understanding and Using Linear Programming; Schrijver, Theory of Linear and Integer Programming;
Williamson & Shmoys, The Design of Approximation Algorithms; Vazirani, Approximation Algorithms; Borodin &
El-Yaniv, Online Computation and Competitive Analysis; Applegate, Bixby, Chvátal & Cook, The Traveling Salesman
Problem; Boyd & Vandenberghe; Goemans & Williamson 1995; Arora, Hazan & Kale 2012; Karlin, Klein & Oveis Gharan 2021.
中文讲义
本讲的中文部分(与英文版对应)。
中文要点与习题解答
本部分区分模型、可行解、最优证书、有限观测与历史定理。十五个生产器按实际 源码哈希使缓存失效,保留实例和独立核验;三次计时取最小值,生成与验证在计时 之外,生产器总耗时不是算法基准。精确整数或有理数证书与浮点构造有不同范围。
- LP 可行域一般是可能无界的凸多面体,本例有界且有六个顶点。单纯形从非负 右端项的可行松弛基开始,没有第一阶段;预算耗尽不等于最优。弱对偶需要双方 可行,有限最优下强对偶给相等目标。影子价格只在有效基区间内是局部边际值。
- Klee–Minty 使用明确的幂系数版本;乘性扰动 Dantzig 实验不同于影子顶点法的 加性高斯平滑分析。椭球有限预算不是不可行证书;近似障碍点用残差修正有理数 上界,不能直接套理想中心点的 m/t。
- TU 需要整数矩阵、整数右端项与界,部分子式检查只能未定。分数背包用精确 比值与分支,避免几乎整数却超重的解;FPTAS 的 nV 是工作模型而非分配内存。
- 度量 TSP 的 Christofides 因子是二分之三;教学 匹配用指数动态规划。根号 n 公式是均匀点的数值渐近预测,不是实例最优值。
- 最大割局部向量值不是认证上界;一般样本使用独立有理数对偶半正定证书。 超平面期望至少为 alpha 倍自身目标,推出 alpha 倍整数最优还需全局优化或 误差控制。有限样本均值不证明通用保证。
- B=10 滑雪租赁的离散比值约 1.53534,连续极限约 1.58198;季节独立于随机 购买日。换页只重放数据访问,模型初始为空、全相联、单位缺失成本。固定循环 不能证明所有确定性策略的下界;随机标记定理针对非自适应请求。
- 乘性权重计期望损失,每个时域重新选择 eta。博弈保留双方平均策略和有限 上下界,另以有理数均衡认证值。凸 KKT 需要原始可行及正则条件,复杂度还要 指定表示、预言机、精度与条件数。三维有限多面体样本不支持一般直径增长律。
六道习题的解答要点:
- 对可行 x,y,有
c^Tx<=y^TAx<=y^Tb。最优目标相等迫使两个非负松弛内积 都为零,进而每项互补乘积都为零。本例(2,0,1)与(1,0,1)都给 13。 - 若原 LP 顶点的某坐标大于一,关联边均有松弛,可以双向微扰,所以不是 顶点。再对大于半且小于一的坐标加 epsilon,对零与半之间的坐标减 epsilon, 反向也做一次。紧边变化抵消,松弛边在足够小扰动下仍合法,故非半整数点不是顶点。
- 租 B-1 天再买的最坏比值为
2-1/B。对购买日 k 的确定性策略,在购买当天 结束季节,比较k-1+B与min(k,B);k<=B 得至少2-1/B,k>B 得至少二。 永不购买无界,B=1 立即购买。不能在看到随机购买日后再沿用此对手。 - 求导
theta/(1-cos theta),驻点满足tan(theta/2)=theta。正根约 2.3311, 比较边界与零端极限得最小值,算出alpha≈0.8786;这不证明局部向量优化收敛。 - 仅移植固定三乘三 LP。零基下标依次为
(3,4,5)、(0,4,5)、(0,4,2), 转轴值为二与二分之一,最终目标行(0,3,0,1,0,1,13)。每个分数运算后约分, 分母保持正,比较用交叉乘法并处理 Bland 平局。此路径约分后的分子绝对值至多 25、分母至多二;更新中间分子至多 1350,比例比较交叉乘积至多 2500,均小于 2 的十二次方,适合指定轨迹的有符号32位字。仍须在模拟器验证,未声称完成移植。 - 有界三维多面体的四个法向量应仿射独立,且有严格正的有理数重心权重,使 加权和为零。这样法向量凸包包含零的邻域,约束在所有方向有界。记录拒绝抽样、 数值容差、活跃面、Euler 检查与所有顶点 BFS;预先指定路由规则并保留失败、 平局和预算耗尽。保存输入与证书,有限成功不能解决多项式 Hirsch 猜想。
四项生产发布门仍单列:连续有声视听审查、中文合成语音听审、全片原生分辨率 审查,以及所选语速下的最终时长批准。
Build the film
python -m videos.cs.cs23.compute # the part's numbers, into .cache/cs23
python tools/build.py cs23 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs23 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs23. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs23.compute
python -m unittest tests.test_cs23_optim -v
python tools/build.py cs23 -q l
python tools/build.py cs23
The source/preview checkpoint is recorded in
docs/qa/computer-science-built-progress.md. Sampled silent previews and automated
speech/alignment checks leave continuous audiovisual/listening review, Chinese
synthesized listening, whole-video native production review and final-pace runtime
approval as separate release gates. The Pebble exercise below is not executed.