Each plant i has a strictly convex quadratic cost curve Ci(Pi) = ai + biPi + ciPi², so its marginal cost — the cost of producing one more unit — grows linearly with output:
dC_i/dP_i = b_i + 2 c_i P_i
Minimizing total cost Σ Ci(Pi) subject to Σ Pi = D is a classic constrained optimization ("economic dispatch"). Its KKT condition says the optimum is reached exactly when every active plant's marginal cost is equal to a common shadow price λ — cheap plants should always be pushed harder than expensive ones until they meet in the middle.
Instead of solving that system algebraically, this simulator finds it the way a numerical optimizer does: penalized gradient descent. Every animation frame nudges each Pi downhill on
L(P) = Σ C_i(P_i) + (ρ/2)(Σ P_i − D)²
P_i ← P_i − α · [ dC_i/dP_i + ρ(Σ P_i − D) ]
then clamps Pi to its plant's [0, Pmax] capacity. The penalty term ρ(ΣP − D) pulls total output toward demand while the plain gradient keeps redistributing load toward whichever plant is currently cheapest — the bars visibly rearrange themselves until every marginal-cost value converges (the "spread" readout → 0) and the output residual → 0.
- Demand shifts the constraint target — watch the whole system re-optimize.
- Fuel price multiplier scales every bi, simulating a market-wide input-cost shock.
- Step size α and stiffness ρ control descent speed vs. stability — push either too high and the bars overshoot and oscillate, exactly as real gradient methods do.
This is the same equal-marginal-cost principle used in real power-grid dispatch, multi-factory production planning and cloud workload cost balancing.