Part 1 · Optimization

The simplex method, by hand and in C++

27 October 20262 min readLevel: Beginner to intermediateNeeds: Linear algebra, C++Türkçe oku

Every linear program you hand to a commercial solver is, at its heart, a search over the corners of a polyhedron. The simplex method makes that search concrete: start at one corner, move along an edge to a neighbouring corner that is better, and stop when no neighbour improves the objective.

Writing it yourself once is the fastest way to stop treating the solver as a black box. You start to understand why a model is slow, why it reports “unbounded”, and what a dual value actually is.

The problem

We solve linear programs in this form:

max⁡x  c⊤xs.t.Ax≤b,  x≥0,  b≥0\max_{x}\; c^\top x \quad \text{s.t.} \quad A x \le b,\; x \ge 0,\; b \ge 0

The condition b≥0b \ge 0 is a simplification for this first version: it means x=0x = 0 is feasible, so we can start from the corner at the origin. Adding a slack variable si≥0s_i \ge 0 to each row turns every inequality into an equality, Ax+s=bA x + s = b, and the slacks form our first basis.

One iteration

  1. Pick an entering variable. In the objective row, a negative reduced cost means increasing that variable improves the objective. Pick the most negative one (Dantzig’s rule).
  2. Pick a leaving variable. Increase the entering variable until the first basic variable hits zero. That is the minimum ratio test: among rows with a positive coefficient in the entering column, choose the smallest bi/aieb_i / a_{ie}. If no row has a positive coefficient, the objective can grow forever: the problem is unbounded.
  3. Pivot. Divide the leaving row by the pivot element, then eliminate the entering column from every other row, including the objective row.

When no reduced cost is negative, the current corner is optimal.

In C++

#include <cmath>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <vector>

using Matrix = std::vector<std::vector<double>>;

// Maximize c^T x subject to A x <= b, x >= 0, with b >= 0.
// Returns the optimal objective value and writes the solution into x.
double simplex(const Matrix& A, const std::vector<double>& b,
               const std::vector<double>& c, std::vector<double>& x) {
    const int m = A.size(), n = c.size();
    const double eps = 1e-9;

    // Tableau: m constraint rows + 1 objective row,
    // n original + m slack columns + 1 right-hand side.
    Matrix T(m + 1, std::vector<double>(n + m + 1, 0.0));
    std::vector<int> basis(m);
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) T[i][j] = A[i][j];
        T[i][n + i] = 1.0;              // slack variable s_i
        T[i][n + m] = b[i];
        basis[i] = n + i;               // start from the all-slack basis
    }
    for (int j = 0; j < n; ++j) T[m][j] = -c[j];   // row for z - c^T x = 0

    while (true) {
        // Entering column: most negative reduced cost (Dantzig's rule).
        int e = -1;
        for (int j = 0; j < n + m; ++j)
            if (T[m][j] < -eps && (e == -1 || T[m][j] < T[m][e])) e = j;
        if (e == -1) break;             // no improving direction: optimal

        // Leaving row: minimum ratio test keeps the solution feasible.
        int l = -1;
        double best = std::numeric_limits<double>::infinity();
        for (int i = 0; i < m; ++i)
            if (T[i][e] > eps) {
                double r = T[i][n + m] / T[i][e];
                if (r < best) { best = r; l = i; }
            }
        if (l == -1) throw std::runtime_error("problem is unbounded");

        // Pivot on (l, e).
        const double p = T[l][e];
        for (double& v : T[l]) v /= p;
        for (int i = 0; i <= m; ++i)
            if (i != l && std::fabs(T[i][e]) > eps) {
                const double f = T[i][e];
                for (int j = 0; j <= n + m; ++j) T[i][j] -= f * T[l][j];
            }
        basis[l] = e;
    }

    x.assign(n, 0.0);
    for (int i = 0; i < m; ++i)
        if (basis[i] < n) x[basis[i]] = T[i][n + m];
    return T[m][n + m];
}

int main() {
    // max 3 x1 + 5 x2
    // s.t. x1 <= 4,  2 x2 <= 12,  3 x1 + 2 x2 <= 18,  x >= 0
    Matrix A = {{1, 0}, {0, 2}, {3, 2}};
    std::vector<double> b = {4, 12, 18}, c = {3, 5}, x;
    double z = simplex(A, b, c, x);
    std::cout << "z = " << z << ", x = (" << x[0] << ", " << x[1] << ")\n";
}

Compile with g++ -std=c++17 simplex.cpp -o simplex. It prints z = 36, x = (2, 6). Trace it by hand: the first pivot brings in x2x_2 (reduced cost −5-5), the second brings in x1x_1, and the objective row then has no negative entries left.

In practice

This version is correct and deliberately naive. Real solvers differ in ways that matter the day your model gets big:

  • Degeneracy and cycling. When a ratio test ties at zero, Dantzig’s rule can cycle forever. Bland’s rule (pick the lowest index) is a simple, guaranteed fix.
  • Tolerances. The eps above decides what counts as zero. Badly scaled models (coefficients from 10−610^{-6} to 10610^{6}) make every tolerance wrong somewhere. Scale your units before you blame the solver.
  • No dense tableau. Industrial codes use the revised simplex method with a sparse LU factorization of the basis. Same corners, far less arithmetic.

Exercises

  1. Add a counter and print each pivot (l,e)(l, e). Check the path against a drawing of the feasible region.
  2. Change the rule for the entering column to Bland’s rule. Does the number of pivots change on this example?
  3. Remove the restriction b≥0b \ge 0: what goes wrong with the starting basis, and why does that call for a “phase I”?

Discussion

Questions or corrections? Send me an email.

Send an email