AI Wiki中文/EN

Lagrange multipliers

拉格朗日乘子

Balance the objective gradient against equality constraints, then prove what the candidate achieves.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The best unconstrained move may leave the allowed line

Two calibrated scores should stay close to their original values 3 and 1, but their sum must equal 2. Keeping both original scores would violate the requirement. Moving only one score can satisfy the sum, yet may make a larger total squared change than sharing the correction.

The best adjustment is (2,0): both coordinates decrease by one. At this point the ordinary loss gradient is not zero. It points perpendicular to the allowed line, so there is no first-order improvement along the line. A Lagrange multiplier records the constraint force that balances this gradient.

Coordinates in this example are unrestricted real numbers; there is no nonnegativity constraint. If scores had to remain nonnegative for every total, that would be a different problem with inequalities. Read partial derivatives and orthogonal projection first.

Stationarity must respect feasible directions

For a differentiable objective f and equality constraint c(x)=0, choose the sign convention:

L(x,ν)=f(x)+νc(x),∇f(x∗)+ν∗∇c(x∗)=0,c(x∗)=0.\mathcal L(x,\nu)=f(x)+\nu c(x),\qquad \nabla f(x^*)+\nu^*\nabla c(x^*)=0,\qquad c(x^*)=0.

At a regular local constrained optimum, this stationarity condition is necessary. For one continuously differentiable constraint, regularity includes a nonzero constraint gradient. Feasible tangent directions are perpendicular to that gradient; the objective gradient must also be perpendicular to every tangent direction, so it lies along the constraint normal. OpenStax §4.8 gives this geometry and the nonzero-gradient condition. Its multiplier equation uses the opposite sign arrangement; our convention keeps the constraint added to the objective as in Convex Optimization §5.1.

With several equality constraints, independent constraint gradients make the tangent-space argument work: the loss gradient lies in their span, with one multiplier per constraint. Equality multipliers have no nonnegative-sign restriction. Multiplying the constraint equation by a nonzero constant changes the numerical multiplier, while leaving the feasible points unchanged.

Solve the calibration problem explicitly

Let a contain n original scores and b be the required sum. The objective is half the squared Euclidean adjustment:

min⁡x 12∑i=1n(xi−ai)2subject to∑i=1nxi=b.\min_x\ \frac12\sum_{i=1}^{n}(x_i-a_i)^2 \quad\text{subject to}\quad\sum_{i=1}^{n}x_i=b.

The gradient of the constraint is the all-ones vector, which is nonzero for positive n. Each stationarity equation says xᵢ−aᵢ+ν=0. Summing the equations and imposing the required total gives:

ν∗=∑iai−bn,xi∗=ai−ν∗.\nu^*=\frac{\sum_i a_i-b}{n},\qquad x_i^*=a_i-\nu^*.

All coordinates share the same correction because their squared deviations have equal weights. Different penalty weights would distribute the correction differently. This closed form takes O(n) work; no iterative optimizer is needed for this specific problem.

Stationarity alone is not our proof of a minimum. Write any other feasible point as x*+d, where the entries of d sum to zero. Expanding the squared norm produces a cross term (x*−a)ᵀd=−ν*Σdᵢ=0. Hence:

f(x∗+d)=f(x∗)+12∥d∥22whenever∑idi=0.f(x^*+d)=f(x^*)+\frac12\|d\|_2^2\quad\text{whenever}\quad\sum_i d_i=0.

Every nonzero feasible displacement increases loss. This proves the solution is the unique global minimum. The argument uses the particular positive quadratic objective and affine constraint; a generic Lagrange stationary point may instead be a maximum or a saddle.

Read the multiplier as a local sensitivity, with its sign convention

The optimal value as a function of the required total is V(b)=(Σaᵢ−b)²/(2n). Differentiating gives V′(b)=−ν*. At a=(3,1), b=2, ν*=1, so a small increase in the required total initially reduces optimal loss at rate one per unit. This is a local derivative, not the exact change for a whole unit. Increasing b to 3 changes V from 1 to 1/4, a decrease of 3/4.

Use exact fractions to verify feasibility and optimality

The complete Python 3.12 program accepts 1–32 rational target coordinates and a rational total. Booleans and floating-point values are rejected. It computes the multiplier and candidate, checks the equations, and tests the exact loss change on several feasible displacements. Those samples illustrate the identity proved above; the proof covers every real feasible displacement.

from fractions import Fraction as F


def project_sum(values,total):
    if type(values) not in (list,tuple) or not 1 <= len(values) <= 32:
        raise ValueError('1 to 32 target coordinates required')
    if any(type(v) not in (int,F) for v in (*values,total)):
        raise ValueError('integer or Fraction inputs required')
    a=[F(v) for v in values];total=F(total)
    multiplier=(sum(a)-total)/len(a)
    x=[v-multiplier for v in a]
    loss=sum((u-v)**2 for u,v in zip(x,a))/2
    assert sum(x)==total
    assert all(u-v+multiplier==0 for u,v in zip(x,a))
    return x,multiplier,loss


if __name__ == '__main__':
    for total in (2,3):
        x,nu,loss=project_sum([3,1],total)
        print('total='+str(total),'x='+str([str(v) for v in x]),
              'multiplier='+str(nu),'loss='+str(loss))
    x,nu,loss=project_sum([3,1],2)
    for t in (F(-2),F(1,2),F(3)):
        z=[x[0]+t,x[1]-t]
        other=sum((u-v)**2 for u,v in zip(z,[3,1]))/2
        assert other==loss+t*t
    print('feasible-direction loss = optimum + t^2')

Output:

total=2 x=['2', '0'] multiplier=1 loss=1
total=3 x=['5/2', '1/2'] multiplier=1/2 loss=1/4
feasible-direction loss = optimum + t^2

The first row is the original sum-2 problem. The second confirms that changing the total changes both the optimal point and the multiplier. The final checks use directions (t,−t), whose coordinate sum is zero. Their loss increase is t², including when t is negative.

The implementation uses O(n) arithmetic and O(n) output storage. Exact fractions avoid rounding in these small examples, but numerator/denominator growth affects bit cost. In large constrained systems, solving the stationarity equations can require a linear or nonlinear solver and a separate conditioning analysis.

A multiplier is not a universal certificate

Regularity matters. Minimize f(x)=x subject to c(x)=x²=0. The only feasible point is zero, so it is a minimum over that feasible set. Yet f′(0)+νc′(0)=1 can never vanish. The constraint gradient is zero, so the regularity assumption fails. Rewriting the same feasible set as x=0 restores a regular equation and admits a multiplier. Constraint representation can therefore affect the applicability of a theorem.

For nonlinear constraints, local candidates may lie on different disconnected pieces or include maxima. Check feasibility, compare candidates where possible and use appropriate second-order or global arguments. Multipliers are additional unknowns, not a penalty coefficient chosen arbitrarily by the programmer.

Inequality constraints need sign and complementary-slackness conditions. KKT conditions develop those rules; duality explains when multipliers produce bounds and optimality certificates. Do not add a nonnegative-sign rule to equality multipliers just because inequality multipliers use one.

Keep the constraint representation in view

  1. For target (3,1) and required total 2, check the gradient balance at (2,0).

Answer 1: The loss gradient is (−1,−1), the constraint gradient is (1,1), and ν=1 makes their sum zero. The coordinates also sum to 2.

  1. Replace the constraint c(x)=0 by 2c(x)=0. What happens to the multiplier under the same plus-sign convention?

Answer 2: It becomes ν/2 so that its product with the doubled constraint gradient stays unchanged. The primal solution and objective are unchanged.

  1. Does ν=1 at b=2 predict an exact loss reduction of one when b becomes 3?

Answer 3: No. It predicts the local derivative V′(2)=−1. The actual finite reduction is 3/4 because V is quadratic in b.

  1. Why can minimizing x under x²=0 have no Lagrange multiplier at its feasible optimum?

Answer 4: The constraint gradient vanishes at zero, violating the regularity assumption. The stationarity equation remains 1=0 for every multiplier, even though the feasible set contains only the optimum.

Move from geometric balance to constrained algorithms

OpenStax gives the geometric necessary condition; Boyd and Vandenberghe place multipliers inside the Lagrangian framework. The calibration example connects that framework to an exact projection and a value-sensitivity calculation, without requiring an optimization package.

For a next exercise, replace the sum by a weighted linear constraint wᵀx=b with nonzero w. Derive the correction along w, then check that feasible displacements orthogonal to w increase the objective by half their squared norm. After that, study KKT before adding coordinate bounds to the calibration problem.

Make a prediction, then check

For equality constraints, must the Lagrange multiplier be nonnegative?

Choose one answer

Learning objectives

  • Derive an equality-constrained projection with its multiplier.
  • Separate regularity, stationarity and a proof of global optimality.

Prerequisites & connections

Explore related knowledge →

References

  1. Calculus Volume 3 — 4.8 Lagrange Multipliers
    Gilbert Strang; Edwin Herman; OpenStax · 2016
  2. Convex Optimization
    Stephen Boyd; Lieven Vandenberghe · 2004

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-agent authored technical review: primary-source locations, explicit assumptions, derivations, literal or exact computational checks, and bilingual review; not independent human or second-agent peer review.

  • Single-agent authored technical review: source locations, stated domains and assumptions, derivations, literal or exact reference cases and matching bilingual programs/exercises. Not independent human or second-agent peer review.
  • Four focused tests passed on CPython 3.12.4. Exact Fraction examples are used except for the explicitly floating-point damped Newton experiment. Strict bilingual MDX/KaTeX rendering gives four equations, six anchors and four answers per language; repository publication checks are recorded separately.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.