Numerous optimization algorithms exist, and choosing among them is rarely straightforward. During my PhD research I found differential evolution (DE) to be the most stable of the evolutionary algorithms I tested, outperforming the others in many structural applications. Its simplicity and versatility are the reasons I have used it in many of my optimization articles, and especially in my publication "A comparative study of differential evolution variants in constrained structural optimization", which has attracted a lot of interest and many citations. In this article, I try to demystify every aspect of the algorithm in a clear and simple way, with a practical example, code and results.
Introduction to Differential Evolution
Differential Evolution (DE) is a population-based, stochastic optimizer introduced by Rainer Storn and Kenneth Price (technical report 1995; journal article 1997). It minimizes a real-valued objective function over a continuous search space and needs no derivatives: it only ever evaluates the objective. That makes it a natural choice for black-box problems, where the function comes from a simulation or an experiment and may be non-differentiable, noisy, or riddled with local minima.
The method is popular because it is simple (about twenty lines of code), has only three control parameters (the population size $NP$, the scale factor $F$ and the crossover rate $CR$), and is surprisingly robust. However, it is not efficient: it typically needs thousands of function evaluations, it gives no mathematical guarantee of reaching the global optimum in finite time, and constraints need explicit handling. For a smooth, convex problem a gradient-based method is far cheaper (we will compare against one at the end).
Algorithm Overview
DE maintains a population of $NP$ candidate vectors $\mathbf{x}_1,\dots,\mathbf{x}_{NP}\in\mathbb{R}^D$. In every generation $g$, each vector in turn plays the role of the target $\mathbf{x}_i$ and is challenged by a trial vector $\mathbf{u}_i$ built in two stages, mutation and crossover. Selection then decides which of the two survives into generation $g+1$.
Control Parameters
| Parameter | Meaning | Usual range | Effect |
|---|---|---|---|
| $NP$ | Population size | $5D$ to $10D$ (at least 4) | Larger: more diversity and robustness, more evaluations per generation |
| $F$ | Scale factor of the difference vector | $0.4$ to $1.0$ | Larger: longer exploratory steps; too small: the population contracts before it finds the optimum |
| $CR$ | Crossover rate | $0.1$ to $0.9$ | Larger: the trial changes many coordinates at once; smaller: it changes few |
| $G_{\max}$ | Number of generations | problem dependent | Sets the evaluation budget, $NP \cdot G_{\max}$ |
The ranges are common rules of thumb from the DE literature, not guarantees. The parameter study below shows how sensitive the outcome can be, even on a two-dimensional problem.
Step 1 – Initialization
The initial population is drawn uniformly at random from the search box, so that it covers the whole domain:
Here $L_j$ and $U_j$ are the lower and upper bounds of coordinate $j$, and $\text{rand}_{[0,1]}$ is a fresh uniform random number for every entry. A fixed random seed makes a run reproducible, which matters when you compare parameter settings.
Step 2 – Mutation (DE/rand/1)
The classic strategy is called DE/rand/1: rand because the base vector is chosen at random,
1 because one difference vector is used. Three distinct individuals
$\mathbf{r}_1,\mathbf{r}_2,\mathbf{r}_3$, all different from the target $\mathbf{x}_i$, are drawn at random and
combined into the mutant vector
Geometrically, $\mathbf{r}_2-\mathbf{r}_3$ is the arrow that points from one random member of the population to another. We copy this arrow, shrink or stretch it by the factor $F$, and attach it to the base vector $\mathbf{r}_1$ (Fig. 2). Because the arrow is made from the population itself, it is long while the population is widely spread and short once the population has collapsed onto a minimum – this is the self-scaling behaviour that gives DE its name.
Any component of $\mathbf{v}_i$ that leaves the search box is clipped to the nearest bound. Other common remedies are to reflect the component back into the box or to redraw it at random.
Other Mutation Strategies
| Strategy | Mutant vector | Character |
|---|---|---|
DE/rand/1 | $\mathbf{r}_1 + F(\mathbf{r}_2-\mathbf{r}_3)$ | Exploratory, robust default |
DE/best/1 | $\mathbf{x}_{best} + F(\mathbf{r}_1-\mathbf{r}_2)$ | Fast convergence, higher risk of premature convergence |
DE/rand/2 | $\mathbf{r}_1 + F(\mathbf{r}_2-\mathbf{r}_3) + F(\mathbf{r}_4-\mathbf{r}_5)$ | More diversity, slower |
DE/current-to-best/1 | $\mathbf{x}_i + F(\mathbf{x}_{best}-\mathbf{x}_i) + F(\mathbf{r}_1-\mathbf{r}_2)$ | Balance between exploitation and exploration |
Step 3 – Crossover (Binomial)
The mutant is rarely used as it stands. Instead, the trial vector $\mathbf{u}_i$ inherits some components from the mutant and the rest from the target, which preserves part of the information that the target already carries:
$j_\text{rand}$ is one randomly chosen coordinate that is always taken from the mutant. Without it, with probability $(1-CR)^D$ the trial would be an exact copy of the target and the evaluation would be wasted.
On average $1+(D-1)\,CR$ coordinates come from the mutant. A high $CR$ therefore moves the trial vector in many directions at once, which suits problems whose variables interact (for example, a constraint along a diagonal). A low $CR$ changes only a few coordinates at a time, which suits problems that can be solved one variable at a time. In two dimensions the picture of Fig. 2 makes this concrete: the trial is $\mathbf{v}$ with probability $CR$, and $\mathbf{u}_a$ or $\mathbf{u}_b$ with probability $(1-CR)/2$ each.
Step 4 – Greedy Selection
The trial vector replaces its target only if it is at least as good:
The comparison is strictly one-to-one: a trial competes only with its own target, never with the rest of the population. This is elitist (the best objective value in the population can never get worse) and it preserves diversity, because a mediocre individual survives as long as nobody has beaten its own trial. Using $\le$ rather than $<$ lets the population drift across flat regions. In our implementation all trials of a generation are computed from the old population and the replacements are applied together (a synchronous update).
Handling Constraints with a Penalty
DE itself knows nothing about constraints. The simplest remedy is an exterior penalty: add to the objective a term that is zero for feasible points and grows with the amount of violation,
DE then minimizes $\tilde{f}$ as if it were an ordinary unconstrained function. The weight $\rho$ matters. If it is too small, the optimizer prefers to sit in the infeasible region where $f$ is lower. For this absolute-value penalty there is a clean rule: the penalty is exact, meaning that its minimizer coincides with the constrained minimizer, as soon as $\rho$ is larger than the Lagrange multiplier $\lambda$ of the active constraint. We will compute $\lambda$ in the worked example. Making $\rho$ far larger than necessary is not free either, because it turns the boundary into a steep cliff and makes the landscape badly scaled.
Worked Example – A Constrained Two-Variable Problem
We minimize the squared distance to the point $(2,3)$ while staying on one side of a line:
The unconstrained minimum $(2,3)$ has $x+y=5$, so it violates the constraint. The constraint is therefore active: the solution must lie on the line $x+y=4$, which is exactly what makes this an instructive test for a penalty method. (Had the constraint been inactive at the optimum, the penalty would never come into play.)
The Exact Answer, for Reference
Because the problem is so small we can solve it by hand and have a ground truth to check DE against. At a constrained minimum the gradient of $f$ must be a multiple of the gradient of the active constraint:
The first equation forces $x - 2 = y - 3$, that is $y = x + 1$. Together with $x+y=4$ this gives $x^*=1.5$, $y^*=2.5$ and $\lambda = -2(x^*-2) = 1 > 0$. The optimal value is $f^* = (-0.5)^2 + (-0.5)^2 = 0.5$. Geometrically, the optimum is the point of the line closest to $(2,3)$, where the contour $f=0.5$ just touches the constraint line (Fig. 4). Since $\lambda = 1$, any penalty weight $\rho > 1$ is exact; we use $\rho = 100$.
Python Implementation
The listing below is complete and was run to produce every number and figure in this article (NumPy 2.5, Python 3.14). The penalty is the absolute-value penalty from above; selection and update are synchronous.
import numpy as np
# ---- problem -------------------------------------------------------
def objective(p):
x, y = p
return (x - 2) ** 2 + (y - 3) ** 2
def violation(p):
"""Amount by which g(x, y) = x + y - 4 <= 0 is violated."""
x, y = p
return max(0.0, x + y - 4)
RHO = 100.0
def penalized(p):
return objective(p) + RHO * violation(p)
# ---- differential evolution (DE/rand/1/bin) ------------------------
def differential_evolution(func, bounds, NP=20, F=0.8, CR=0.7,
G_max=200, seed=42):
rng = np.random.default_rng(seed)
lo, hi = np.array(bounds, dtype=float).T
D = len(lo)
pop = lo + rng.random((NP, D)) * (hi - lo) # initialization
fit = np.array([func(p) for p in pop])
history = [(pop.copy(), fit.copy())]
for g in range(G_max):
new_pop, new_fit = pop.copy(), fit.copy()
for i in range(NP):
# mutation: three distinct individuals, none equal to target
others = [j for j in range(NP) if j != i]
r1, r2, r3 = rng.choice(others, 3, replace=False)
v = np.clip(pop[r1] + F * (pop[r2] - pop[r3]), lo, hi)
# binomial crossover; one component is forced from the mutant
mask = rng.random(D) <= CR
mask[rng.integers(D)] = True
u = np.where(mask, v, pop[i])
# greedy selection
fu = func(u)
if fu <= fit[i]:
new_pop[i], new_fit[i] = u, fu
pop, fit = new_pop, new_fit
history.append((pop.copy(), fit.copy()))
best = np.argmin(fit)
return pop[best], fit[best], history
bounds = [(0, 10), (0, 10)]
best, f_best, history = differential_evolution(
penalized, bounds, NP=20, F=0.8, CR=0.7, G_max=200, seed=42)
print(f"best x = {best[0]:.6f}, y = {best[1]:.6f}")
print(f"f(x, y) = {objective(best):.8f}, x + y = {best.sum():.6f}")
Running the driver gives
best x = 1.500000, y = 2.500000
f(x, y) = 0.50000000, x + y = 4.000000
The solution agrees with the analytic result to six decimals. The run used $NP\cdot G_{\max} + NP = 4020$ objective evaluations.
Watching the Population Converge
Fig. 5 shows the 20 individuals at four moments of the run with seed 42. At generation 0 they are scattered over the whole box and none of them is feasible, so the best individual (orange) is simply the one that violates the constraint least. Within three generations twelve individuals have landed in the feasible triangle. By generation 10, 19 of the 20 are feasible and the best one is already close to the optimum, but the population is still spread out. By generation 30 it has contracted into a tight cluster on the line $x+y=4$ – the shrinking differences $\mathbf{r}_2-\mathbf{r}_3$ at work.
Convergence History
The table lists the best individual of the same run (error $=\tilde f - f^*$ with $f^*=0.5$).
| Generation | Best $\tilde{f}$ | $x$ | $y$ | $x+y$ | Error $\tilde f - f^*$ |
|---|---|---|---|---|---|
| 0 | 124.202430 | 4.6672 | 0.4380 | 5.1052 | 1.2 × 102 |
| 1 | 2.898394 | 0.6139 | 2.0115 | 2.6254 | 2.4 × 100 |
| 5 | 1.080699 | 0.9605 | 2.9894 | 3.9499 | 5.8 × 10−1 |
| 10 | 0.538528 | 1.5343 | 2.4329 | 3.9671 | 3.9 × 10−2 |
| 30 | 0.502082 | 1.5206 | 2.4782 | 3.9988 | 2.1 × 10−3 |
| 50 | 0.500126 | 1.5023 | 2.4976 | 3.9999 | 1.3 × 10−4 |
| 100 | 0.500000 | 1.5000 | 2.5000 | 4.0000 | 7.3 × 10−8 |
| 150 | 0.500000 | 1.5000 | 2.5000 | 4.0000 | 1.0 × 10−10 |
| 200 | 0.500000 | 1.5000 | 2.5000 | 4.0000 | 2.2 × 10−13 |
Note that from generation 1 on the best individual is feasible ($x+y\le 4$). It then slides along the boundary towards the optimum from the inside (Fig. 7).
Convergence Plot
On a logarithmic axis the error falls almost linearly, that is, geometrically fast: it shrinks by roughly a factor of ten every 15 to 18 generations once the population has found the right region (from generation 30 to 200 the error falls from $2\cdot10^{-3}$ to $2\cdot10^{-13}$, ten orders of magnitude). The stairs in the curve of the best individual are characteristic of DE: improvement happens in bursts, whenever a trial vector beats the current best. The population mean (orange) lags behind because the average individual is still improving long after the best one has nearly converged. The thirty grey curves come from independent runs with seeds 0–29; all of them reached an error below $2\cdot10^{-12}$, so the behaviour is not a lucky seed.
Trajectory of the Best Individual
The left panel shows the coordinates of the best individual: after a few generations of large jumps, they settle at $x^*=1.5$ and $y^*=2.5$. The right panel plots the constraint value $x+y$. The best individual starts infeasible ($x+y\approx 5.1$), becomes feasible after the first generation and then creeps up to the limit $4$ from below, which is the signature of an active constraint: the optimum sits on the boundary.
How Much Do the Parameters Matter?
To see the influence of $F$, $CR$ and $NP$, the same problem was solved 30 times (seeds 0–29) for each of five settings. Fig. 8 shows the median error over the 30 runs; the table counts how many runs reached an error below $10^{-6}$ within 200 generations and how many generations the successful runs needed (median).
| Setting | Runs with error < $10^{-6}$ | Median generations needed |
|---|---|---|
| F = 0.8, CR = 0.7 (baseline) | 30 / 30 | 94 |
| F = 0.5, CR = 0.9 | 28 / 30 | 58 |
| F = 0.8, CR = 0.1 | 0 / 30 | – |
| F = 0.2, CR = 0.7 | 2 / 30 | 82 |
| NP = 8 (F = 0.8, CR = 0.7) | 25 / 30 | 97 |
The median is taken over the successful runs only, so for $F=0.2$ it rests on just two runs.
- Baseline ($F=0.8$, $CR=0.7$) solved all 30 runs, but needed a median of 94 generations against 58 for the fastest setting.
- Smaller $F$, larger $CR$ ($0.5$, $0.9$) was the fastest, but two of 30 runs did not reach $10^{-6}$ within 200 generations: speed was bought with robustness.
- Low $CR$ ($0.1$) failed in every run. In two dimensions only about 10 % of the trial vectors then change both coordinates, so the search moves almost exclusively parallel to the axes, and it cannot follow a boundary that runs diagonally.
- Very small $F$ ($0.2$) stalls around an error of $10^{-3}$: the differences shrink faster than the population approaches the optimum, so the population contracts prematurely.
- A small population ($NP=8$) works most of the time but failed in 5 of 30 runs, because too few individuals reduce diversity.
Cross-Check with SciPy
In practice you would rarely write DE yourself. SciPy ships a well-tested version that also supports other mutation strategies, vectorized evaluation and general constraints:
import numpy as np
from scipy.optimize import differential_evolution, LinearConstraint
f = lambda p: (p[0] - 2) ** 2 + (p[1] - 3) ** 2
res = differential_evolution(
f, [(0, 10), (0, 10)],
constraints=LinearConstraint([[1, 1]], -np.inf, 4), # x + y <= 4
seed=42, tol=1e-10, polish=False)
print(res.x, res.fun, res.nfev)
Output:
[1.50000018 2.49999982] 0.5000000000002502 1464
It reproduces $(1.5,\,2.5)$ with $f=0.5$, again to six decimals. For comparison, the gradient-based SLSQP method
(scipy.optimize.minimize) finds the same solution from a starting point of its choice in a handful of iterations. This is the
expected division of labour: for a smooth, convex problem like this one a gradient-based solver is far cheaper, while DE earns its keep
when the objective is non-smooth, noisy or has many local minima, and gradients are unavailable or unreliable.
Best solution: $x = 1.500000$, $y = 2.500000$ – objective $f = 0.50000000$
Constraint: $x + y = 4.000000 \le 4$ ✔ | bounds $0\le x,y\le 10$ ✔
Analytic optimum: $(1.5,\,2.5)$, $f^*=0.5$ – final error $2.2\cdot 10^{-13}$
Practical Guidance
- Scale the variables. DE draws every coordinate from its bounds, so wildly different ranges (for instance $[0,1]$ and $[0,10^6]$) slow it down. Rescale to comparable ranges.
- Choose the budget in evaluations. The cost is $NP\cdot G_{\max}$ evaluations; set $NP$ from the dimension and $G_{\max}$ from the budget.
- Run several seeds. DE is stochastic. Agreement between independent runs is the best evidence that you found the global optimum.
- Raise $NP$ for multimodal problems and use a larger $F$ if the population converges too early.
- Polish at the end. A short run of a local, gradient-based optimizer started from the DE solution (SciPy's
polish=True) gives machine-precision accuracy cheaply. - Stop on convergence. Besides $G_{\max}$, monitor the spread of the population or the improvement of the best value.
Summary of Key Formulas
| Step | Formula | Description |
|---|---|---|
| Initialization | $x_{i,j} = L_j + \text{rand}\cdot(U_j-L_j)$ | Uniform random sampling within the bounds |
| Mutation | $\mathbf{v}_i = \mathbf{r}_1 + F(\mathbf{r}_2 - \mathbf{r}_3)$ | Scaled difference added to a random base vector |
| Crossover | $u_{i,j} = v_{i,j}$ if $\text{rand}\le CR$ or $j=j_\text{rand}$, else $x_{i,j}$ | Binomial, component by component |
| Selection | $\mathbf{x}_{i,g+1} = \mathbf{u}_{i}$ if $f(\mathbf{u}_i) \le f(\mathbf{x}_{i,g})$ | Greedy, one-to-one replacement |
| Penalty | $\tilde{f}=f+\rho\sum_k\max(0,g_k)$ | Exact if $\rho$ exceeds the Lagrange multiplier |
References
- R. Storn and K. Price, “Differential Evolution – A Simple and Efficient Heuristic for Global Optimization over Continuous Spaces,” Journal of Global Optimization 11 (1997), 341–359.
- K. V. Price, R. M. Storn and J. A. Lampinen, Differential Evolution: A Practical Approach to Global Optimization, Springer, 2005.
- K. Deb, “An efficient constraint handling method for genetic algorithms,” Computer Methods in Applied Mechanics and Engineering 186 (2000), 311–338.