Sam Austinon December 1, 202620 min read

Simulated Annealing in Python: How to Escape Local Optima

Simulated Annealing in Python: How to Escape Local Optima
Contents

Figure 1: Simulated Annealing in Python: How to Escape Local Optima — a road winding between ridges, the picture of a search that has to leave one peak to reach a better one

Hill climbing has one rule: if a move makes things better, take it. That rule is fast and simple, and it marches you straight to the nearest peak, even when a much taller one stands across the valley. Simulated annealing (SA) adds one tiny twist: sometimes it takes a move that makes things worse. That occasional step backward lets it climb out of local optima, and it takes about ten lines of Python to implement.

I can't claim I've tuned SA on your problem, and I haven't run the code below in this conversation, so test it yourself. Sources are listed at the end rather than inline. IMO, SA is one of the best algorithms to learn because it forces you to confront the exploration-versus-exploitation tradeoff directly: one number, the temperature, controls it. Ready to heat things up?

The Idea: Cool Slowly and Take Some Bad Moves

SA borrows from metallurgy. Heat a metal, then cool it slowly, and its atoms settle into a low-energy crystal. Cool it fast, and you get a brittle, disordered mess. An optimization version maps the physics directly: the objective function plays the role of energy, the current solution plays the role of the atomic configuration, and a temperature schedule controls how quickly the acceptance window narrows.

Kirkpatrick, Gelatt, and Vecchi popularized the method in 1983, applied it to the traveling salesman problem, and gave it the name simulated annealing [1]. Similar ideas appeared independently several times, including Pincus in 1970 and Černý in 1985 [3], and the method adapts the Metropolis algorithm from 1953 [2]. The Metropolis acceptance rule drives it:

  • If the move improves the objective (ΔE ≤ 0), accept it.
  • If the move worsens it (ΔE > 0), accept it with probability exp(−ΔE / T).

High temperature means high acceptance of worse moves, which gives strong exploration. Low temperature means low acceptance, which gives strong exploitation and local refinement. As the temperature falls, SA morphs from a random wanderer into a hill climber.

How Likely Is a Bad Move?

Say a candidate move worsens the objective by 2:

At T = 10,  the acceptance probability is exp(−0.2) ≈ 0.82
At T = 1,   it's exp(−2) ≈ 0.14
At T = 0.1, it's exp(−20) ≈ 2 × 10⁻⁹

Same move, completely different behavior. That's the whole algorithm in three numbers.

The Ingredients You Must Choose

Every SA implementation needs four decisions:

  1. A neighborhood (proposal mechanism): how do you generate a nearby candidate? Course notes describe it as often a uniform random choice from the neighbors of the current solution.
  2. An initial temperature T₀: it depends on the problem. One source says it's chosen so the acceptance ratio starts close to one.
  3. A cooling schedule: how T decreases. Geometric cooling, T ← αT, is the most common choice, and NUS lecture notes give α = 0.95 as an example.
  4. A stopping rule: a final temperature, an iteration budget, or no improvement combined with a low acceptance ratio (the NUS notes mention stopping when improvement stalls and the acceptance ratio falls below 2%).

Other schedules exist: linear, inverse-linear, logarithmic, and exponential. A patent-literature review of the original paper notes Kirkpatrick and colleagues described geometric, linear, and logarithmic schedules and concluded none gives a dramatic advantage over geometric. So start with geometric, and spend your tuning effort elsewhere.

Example 1: Escaping a Bumpy Landscape

Here's a one-dimensional function with many local minima: a Rastrigin-style curve whose global minimum sits at x = 0 with value 0, with other local minima near every integer. I haven't run this, so test it:

import math, random

def f(x):
    return x**2 + 10 * (1 - math.cos(2 * math.pi * x))    # global min at 0; local minima near integers

def hill_climb(x, iters=5000, sigma=0.1, rng=random):
    fx = f(x)
    for _ in range(iters):
        y = x + rng.gauss(0, sigma)
        fy = f(y)
        if fy < fx:
            x, fx = y, fy
    return x, fx

def anneal(x, iters=5000, T0=10.0, alpha=0.999, sigma=0.5, rng=random):
    fx = f(x); best = (x, fx); T = T0
    for _ in range(iters):
        y = x + rng.gauss(0, sigma)
        fy = f(y)
        d = fy - fx
        if d <= 0 or rng.random() < math.exp(-d / T):
            x, fx = y, fy
            if fx < best[1]:
                best = (x, fx)
        T *= alpha
    return best

def trial(method, n=200, **kw):
    finals = [method(8.3, rng=random.Random(s), **kw)[1] for s in range(n)]
    return sum(v < 0.9 for v in finals) / n, sum(finals) / n     # success = better than any non-global minimum

print("hill climbing:", trial(hill_climb))
print("annealing:    ", trial(anneal))

Starting at x = 8.3, hill climbing should get stuck in the first valley it meets, near x = 8, where f is about 64. The SA run should reach the global basin far more often. The "success" test counts a run as successful when it beats the value of every non-global minimum (about 1 or higher). Verify the numbers yourself, and try different cooling rates to see how fast results degrade.

Example 2: The Traveling Salesman With 2-Opt Moves

For routing, the standard neighborhood is 2-opt: pick two positions and reverse the stretch of the tour between them. Researchers who compared simple swaps with 2-opt in an SA study found the 2-opt neighborhood made a decisive difference, so the neighborhood choice matters as much as the temperature. The code below also computes each move's cost change in constant time, instead of recomputing the whole tour. I haven't run it, so test it:

import math, random

def tour_length(tour, pts):
    n = len(tour)
    return sum(math.dist(pts[tour[i]], pts[tour[(i + 1) % n]]) for i in range(n))

def nearest_neighbor(pts):
    n = len(pts); unvisited = set(range(1, n)); tour = [0]
    while unvisited:
        last = pts[tour[-1]]
        nxt = min(unvisited, key=lambda j: math.dist(pts[j], last))
        tour.append(nxt); unvisited.remove(nxt)
    return tour

def anneal_tsp(pts, T0=0.5, T_end=1e-3, iters=300_000, seed=0):
    rng = random.Random(seed)
    n = len(pts)
    alpha = (T_end / T0) ** (1.0 / iters)                # geometric cooling from T0 to T_end
    tour = list(range(n)); rng.shuffle(tour)
    cur = tour_length(tour, pts)
    best, best_len, T = tour[:], cur, T0
    for _ in range(iters):
        i, j = sorted(rng.sample(range(n), 2))
        if i == 0 and j == n - 1:
            T *= alpha; continue                          # reversing the whole tour changes nothing
        a, b = tour[i - 1], tour[i]
        c, d = tour[j], tour[(j + 1) % n]
        delta = (math.dist(pts[a], pts[c]) + math.dist(pts[b], pts[d])
                 - math.dist(pts[a], pts[b]) - math.dist(pts[c], pts[d]))
        if delta <= 0 or rng.random() < math.exp(-delta / T):
            tour[i:j + 1] = reversed(tour[i:j + 1])      # 2-opt move
            cur += delta
            if cur < best_len:
                best, best_len = tour[:], cur
        T *= alpha
    return best, best_len

rng = random.Random(42)
pts = [(rng.random(), rng.random()) for _ in range(100)]
print("random tour    :", round(tour_length(list(range(100)), pts), 2))
print("nearest neighbor:", round(tour_length(nearest_neighbor(pts), pts), 2))
best, length = anneal_tsp(pts)
print("annealing      :", round(length, 2))

I chose T₀ and T_end to match the scale of the problem: points in the unit square have typical edge lengths well below 1, so a final temperature of 0.001 freezes the tour. If your coordinates are in meters or kilometers, rescale T₀ and T_end to match your distances, or the algorithm will either freeze instantly or never cool.

Then compare honestly. Earlier articles in this series ran OR-Tools and RL policies against nearest neighbor (see TSP with reinforcement learning and OR-Tools vs RL), and the same discipline applies here: race your SA tour against OR-Tools or a dedicated TSP solver, and report how far behind it falls, if at all. SA usually beats nearest neighbor easily, but specialized solvers tend to win on quality for static instances.

Choosing the Initial Temperature

Guessing T₀ is the classic headache. A principled approach: sample some random moves, look at the average worsening Δ, and pick T₀ so that a typical bad move gets accepted with a chosen probability (say 0.8):

def estimate_T0(sample_deltas, p0=0.8):
    worse = [d for d in sample_deltas if d > 0]
    return -(sum(worse) / len(worse)) / math.log(p0)

This follows the advice from the literature I found: start hot enough that the acceptance ratio is high, then cool. Starting too cold wastes the exploration phase, and the NUS notes mention low-temperature starts as a trick when you begin from a good greedy solution and don't want to destroy it.

Tuning the Cooling

  • Cool too fast: premature convergence on a poor solution. A study of simulated annealing for TSP states this directly: a fast schedule can lock in suboptimal solutions, while too-slow cooling raises computation time sharply.
  • Cool too slowly: you waste your time budget.
  • Rule of thumb: use geometric cooling, run enough iterations that final T is tiny compared with your typical Δ, and watch the acceptance ratio fall smoothly.
  • The theory: for any finite problem, the probability that SA terminates at a global optimum approaches 1 as the schedule is extended, but the literature calls this result not particularly helpful in practice, since the required schedule is impractically slow.

Reheating and Restarts

If progress stalls, you can reheat. A paper summarized in the patent review describes strategic oscillation: cool geometrically until progress halts, then raise T to about half its previous starting value, and repeat. Book chapters on SA also list reheating and non-monotonic schedules as adaptive strategies [5]. A simpler option: run several independent SA runs from different seeds and keep the best.

Practical Improvements

  1. Compute deltas incrementally, as the TSP code does. This is often a 10× to 100× speedup, from my experience of how these loops behave, so measure it.
  2. Always remember the best-so-far solution. SA's current state wanders, and the best state may appear mid-run.
  3. Use constraint penalties. Wikipedia notes you can penalize constraint violations as part of the objective. Weight them so violations always cost more than any gain they allow.
  4. Tune the neighborhood before the temperature. A good move set beats clever cooling.
  5. Seed every run and report results across many seeds, because SA is stochastic.
  6. Start from a decent solution (nearest neighbor for TSP, greedy for scheduling) when time is short, with a lower T₀.

A Library Shortcut: SciPy's Dual Annealing

For continuous problems, SciPy offers dual_annealing. A book chapter on optimization compares a SciPy dual annealing solution against its own SA implementation on a continuous test problem. A minimal call looks like this. I haven't run it, so check the signature in your SciPy version [4]:

from scipy.optimize import dual_annealing

res = dual_annealing(lambda v: f(v[0]), bounds=[(-10, 10)], seed=0)
print(res.x, res.fun)

Use it when your variables are continuous and bounded. For discrete problems like routing and scheduling, you'll write your own neighborhood moves, as above.

SA vs. Other Approaches

Course notes list simulated annealing, tabu search, iterated local search, and evolutionary algorithms as the main metaheuristic families, and rate SA and tabu search as the simpler ones. My comparison:

  • Hill climbing with random restarts: simpler and sometimes enough, but SA explores more cleverly.
  • Tabu search: memory-based rather than probability-based.
  • Genetic algorithms: population-based, easier to parallelize (one comparison table I found lists parallelization as difficult for SA and easy for evolutionary methods).
  • Exact solvers (CP-SAT, MIP): use them when the problem fits their modeling language, as the CSP and scheduling article argued, because they can prove optimality.
  • Specialized solvers (like LKH for TSP): usually win on their own turf.
  • Reinforcement learning: can learn heuristics for repeated problem families, but must beat a tuned SA or solver baseline.

SA shines when the objective is odd, noisy, or non-differentiable, when you can define a sensible neighborhood, and when "very good in reasonable time" beats "provably optimal."

Diagnostics

Look inside your runs:

  • Plot cost versus iteration: it should show wild early swings, then smooth descent.
  • Log the acceptance ratio per temperature band: it should start high and fall toward zero.
  • Plot best-so-far: it should drop in steps.
  • Histogram final costs across many seeds: one TSP study did exactly this, comparing 400 runs for each neighborhood choice.
  • Check the final temperature: if the search still accepts many bad moves at the end, you cooled too little.

Common Mistakes to Avoid

  • Mismatching temperature and cost scale. Δ values define the right T range, so rescale.
  • Using a weak neighborhood. Simple swaps often lose badly to 2-opt-style moves.
  • Cooling too fast. You'll get a hill climber with extra steps.
  • Returning the final state instead of the best. The current state may be worse.
  • Recomputing the full cost every step when an incremental delta exists.
  • Running one seed. Report the spread.
  • Skipping the baseline. Compare against a greedy heuristic and a real solver.
  • Treating penalties casually. Weak penalties allow infeasible "solutions."
  • Tuning on one instance. Test across instance sizes and types.

Did you notice that most mistakes involve scale or evaluation, not the algorithm? :/

Best Book to Read

CoverBookDescriptionGet it
Cover of “Simulated Annealing: Theory and Applications” Simulated Annealing: Theory and Applicationsby Peter van Laarhoven and Emile Aarts the foundational treatment of cooling schedules, convergence theory and the practical tuning that the ten-line version hides. View on Amazon

As an Amazon Associate I earn from qualifying purchases. Links on this page are affiliate links, and I may earn a commission at no extra cost to you.

Read it after you have watched a cooling rate wreck your results. The convergence proofs make much more sense once you have seen a schedule that looks fine on paper stall in code.

Wrapping Up

Simulated annealing escapes local optima by accepting worse moves with probability exp(−ΔE/T) and cooling T gradually, turning a wandering search into a focused one. Most of the practical work goes into three choices: a good neighborhood, a temperature range matched to your cost scale, and a cooling schedule slow enough to matter. Add best-so-far tracking, incremental evaluation, and honest baselines, and it becomes a dependable tool.

So run the one-dimensional demo this week, then change the cooling rate from 0.999 to 0.99 and see how the success rate collapses. If a faster schedule ruins your results, you just felt the tradeoff the whole field wrestles with. If it barely changes anything, congratulations: your landscape is friendlier than a Rastrigin curve, and a simpler method may serve you fine. :)

Frequently Asked Questions

What is simulated annealing in simple terms?

Simulated annealing is a search method that usually takes improving moves but sometimes accepts a worse one, with a probability that shrinks as a temperature parameter cools. Accepting occasional bad moves lets the search climb out of a local optimum and explore a better region. It needs only a neighborhood, a temperature schedule and a way to score solutions.

How do I choose the initial temperature?

Match it to the scale of your cost changes, not to the raw cost. Sample some random moves, average the worsening deltas, and set the initial temperature so a typical bad move is accepted about 80 percent of the time. Starting too cold wastes the exploration phase, because most bad moves are rejected immediately.

What cooling schedule should I use?

Geometric cooling, multiplying the temperature by a constant such as 0.95 or 0.999 each step, is the usual default. A schedule that is too fast locks in suboptimal solutions, and one that is too slow wastes your time budget. Because geometric cooling performs comparably to linear and logarithmic schedules, spend your tuning effort on the neighborhood instead.

Why accept worse solutions on purpose?

A strictly improving search gets trapped in the nearest local optimum, which can be far worse than a distant one across a valley. Accepting worse moves with probability exp(-dE/T) lets the search cross that valley while the temperature is still high, then settle into refinement as it cools. The temperature is what turns a wanderer into a hill climber.

Is simulated annealing better than a solver like OR-Tools?

Not for problems a solver can model directly. Exact solvers such as CP-SAT and MIP can prove optimality and usually win on quality for static instances. Simulated annealing is better when the objective is odd, noisy or non-differentiable, when you can define a sensible neighborhood but not a clean model, or when you need a good answer fast without proof.

Sources

  • [1] Kirkpatrick, Gelatt and Vecchi, Optimization by Simulated Annealing (Science, 1983) - the paper that named the method and applied it to the traveling salesman problem: science.org
  • [2] Metropolis, Rosenbluth, Rosenbluth, Teller and Teller, Equation of State Calculations by Fast Computing Machines (1953) - the Metropolis acceptance rule that SA adapts: aip.org
  • [3] V. Černý, Thermodynamical Approach to the Traveling Salesman Problem (1985) - an independent derivation of simulated annealing for routing: link.springer.com
  • [4] SciPy, scipy.optimize.dual_annealing documentation - the built-in annealer for continuous, bounded problems: docs.scipy.org
  • [5] El-Ghazali Talbi, Metaheuristics: From Design to Implementation (2009) - cooling schedules, reheating, tabu search and evolutionary methods side by side: wiley.com

What are You Looking For?

esc