Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Optimization

Cool to Improve.

Greedy optimization gets stuck: it never accepts a worse move, so it settles into the first local minimum it finds and stays there. Simulated annealing borrows from metallurgy — heat a metal and let it cool slowly and its atoms settle into a low-energy crystal. Here, a temperature controls how willing we are to accept a worse solution: always take an improvement, but also accept a worse move with probability e^(−Δ/T). Start hot (bold, escaping local minima), cool slowly (picky, refining). Watch a tangled traveling-salesman tour untangle itself as the temperature falls.

accept worse moves with prob e^(−Δ/T) · cool T slowly · escapes local minima
energy / cost

What we minimize — here the total length of the traveling-salesman tour.

temperature T

Controls boldness: high T accepts many worse moves; low T is nearly greedy.

accept rule

Take any improvement; accept a worse move (Δ>0) with probability e^(−Δ/T).

cooling schedule

T is lowered gradually (e.g. multiplied by 0.99 each step) toward zero.

anneal.js — heat to explore, cool to commit
Ready
A random tour through the cities — long and tangled. Each step proposes a small change (reverse a segment). We always take improvements, and accept worse moves with probability e^(−Δ/T). Auto to anneal.
100
temperature
–
tour length
–
best so far

How it works

The whole method lives in one line: accept a proposed move if it improves the cost, or — if it makes things worse by Δ — accept it anyway with probability e^(−Δ/T). Read that probability at two extremes. When T is large, e^(−Δ/T) is close to 1, so even fairly bad moves are often accepted: the search roams freely and jumps out of local minima. As T falls toward 0, the probability collapses toward 0, so only improvements survive: the search behaves greedily and locks in refinements. Cooling slowly enough gives the search time to explore before it commits — which is what lets it find a near-global optimum on problems where pure greedy gets trapped.

1

Start hot with any solution

Begin from a random solution and a high temperature. At high T the search is willing to accept almost anything, so it explores broadly rather than diving into the nearest dip.

2

Propose a small random change

Perturb the current solution slightly — for a tour, reverse a random segment (a 2-opt move). Measure the change in cost, Δ.

3

Accept by the temperature rule

If Δ ≤ 0 (better or equal), accept. If Δ > 0 (worse), accept anyway with probability e^(−Δ/T). Accepting the occasional worse move is how it climbs out of local minima.

✓

Cool and repeat

Lower the temperature a little and repeat. As T approaches 0 the acceptance of worse moves vanishes and the search settles into a refined, near-optimal solution.

Accepts worse
e^(−Δ/T)
High T
explores
Low T
greedy
Escapes
local minima

The code

# simulated annealing for a minimization problem cur = random_solution(); T = T0 best = cur while T > T_min: nxt = perturb(cur) # small random change delta = cost(nxt) - cost(cur) if delta <= 0 or random() < exp(-delta / T): cur = nxt # accept (worse moves too, prob e^-Δ/T) if cost(cur) < cost(best): best = cur T *= cooling_rate # e.g. 0.99 — cool slowly

Quick check

1. What makes simulated annealing able to escape a local minimum?

2. What happens as the temperature T approaches zero?

3. Why cool the temperature slowly rather than quickly?

FAQ

What is simulated annealing?

A probabilistic optimization method inspired by metal annealing. It makes small random changes, always accepting improvements and sometimes accepting worse moves with probability e^(−Δ/T), where T is a temperature lowered over time. Accepting worse moves lets it escape local minima that trap greedy search.

Why is it called "annealing"?

From metallurgy: annealing heats a metal and cools it slowly so its atoms settle into a low-energy crystal (fast cooling locks in defects). The algorithm mimics this — high temperature lets the search move freely, slow cooling settles it into a low-cost configuration.

How does simulated annealing compare to hill climbing?

Hill climbing accepts only improving moves and stops at the first local optimum. Simulated annealing adds probabilistic acceptance of worse moves, controlled by temperature, letting it escape local optima and find better solutions on rugged landscapes — at the cost of more iterations and tuning the cooling schedule.

What problems is simulated annealing good for?

Hard combinatorial optimization with huge, local-optima-filled search spaces where a good solution suffices: traveling salesman, VLSI placement and routing, scheduling, protein folding models, and layout/assignment problems. It’s a general metaheuristic needing only a cost function and a perturbation.

The picture: the door closes as it cools

uphill moves accepted, by stretch of the run (9 cities, seed 1) 10 → 1.10iterations 0+uphill tried 3,296accepted 1,16335.3% 1.10 → 0.119iterations 5,000+uphill tried 4,359accepted 841.9% 0.119 → 0.0128iterations 10,000+uphill tried 4,462accepted 00.0% 0.0128 → 0.0014iterations 15,000+uphill tried 4,472accepted 00.0% cooling: T falls by 0.05% every step
The page’s 9-city tour with its default settings (t0 = 10, alpha = 0.9995, 20,000 iterations, seed 1), split into four equal stretches. Early on over a third of the worse moves are accepted. By the third stretch the temperature is so low that none are, and the search has turned into plain greedy refinement.

Worked example, step by step

Take the page’s 9 cities (0,0) (1,5) (2,3) (5,1) (6,6) (7,2) (3,7) (8,4) (4,4), start from the order 0, 1, …, 8 (length 42.054), and use the page’s random generator with seed = 1. Each row is one proposal: swap two cities, compute the change in tour length Δ, and accept if Δ < 0 or if a fresh draw r falls below p = e^(−Δ/T). Iterations 7, 8 and 13 drew the same index twice and were skipped, so they do not appear.

IterTSwapΔprDecisionLengthBest
010.002 ↔ 5+1.7000.8440.154accept uphill (r < p)43.75342.054
110.006 ↔ 8+0.0720.9930.586accept uphill (r < p)43.82542.054
29.997 ↔ 5−3.879——accept (downhill)39.94639.946
39.996 ↔ 0−0.076——accept (downhill)39.86939.869
49.980 ↔ 1−3.437——accept (downhill)36.43336.433
59.981 ↔ 6−0.702——accept (downhill)35.73035.730
69.974 ↔ 6+0.8270.9200.883accept uphill (r < p)36.55735.730
99.975 ↔ 2+4.5710.6320.157accept uphill (r < p)41.12835.730
109.961 ↔ 4−1.270——accept (downhill)39.85935.730
119.962 ↔ 6−1.119——accept (downhill)38.73935.730
129.952 ↔ 8+4.7070.6230.966reject (r ≥ p)38.73935.730
149.953 ↔ 7−1.231——accept (downhill)37.50835.730

Read the first and the twelfth row together. At iteration 0 the move is worse by 1.700, but at T = 10 the acceptance probability is 0.844, and the draw 0.154 is below it, so the tour gets longer on purpose. At iteration 12 a worse move of +4.707 has probability 0.623 and the draw 0.966 is above it, so it is rejected and the swap is undone. The Length column wanders (43.753, 43.825, 39.946 … 41.128) while Best only ever goes down, which is why the algorithm keeps a separate best-so-far. Downhill moves never consume a random draw; only uphill ones do. Run to the end, the same seed returns a tour of length 27.060, and a brute-force check over all 40,320 orderings with city 0 fixed gives the same 27.060.

Complexity and trade-offs

CaseTimeSpaceWhy
Simulated annealingO(iterations × cost of one evaluation)O(n)You choose the budget. The page recomputes the whole tour each step (O(n)); a swap changes only a few edges, so a delta formula makes each step O(1).
Brute force over toursO(n!)O(n)8! = 40,320 orders for 9 cities, but 19! = 121,645,100,408,832,000 for 20. Exact, and hopeless past about a dozen cities.
Held–Karp dynamic programmingO(n² · 2ⁿ)O(n · 2ⁿ)Exact, and far better than n!, but the memory grows exponentially.
Greedy hill climbing (T ≈ 0)same per step as annealingO(n)Never accepts a worse move, so it stops at the first local minimum.
Annealing, cooled too fastsame per stepO(n)With alpha = 0.99 the temperature collapses long before the budget ends.

Measured on a 20-city instance (the page’s own test generator, start length 1031.8), five seeds: default annealing gave 368.0, 364.4, 432.2, 367.0, 382.4. Frozen (t0 = 1e-9, hill climbing) gave 415.7, 417.4, 464.8, 434.6, 442.3, and alpha = 0.99 gave 424.2, 452.0, 474.9, 432.0, 451.2. Annealing was shorter on every seed, but it also varied from run to run, and nothing here proves any of those tours is optimal. You pay in guarantees: you get a good answer for a bounded budget, not the best answer.

Common mistakes

  • Returning the final state instead of the best

    The current tour is allowed to get worse, so it can end above the best it ever visited. On the 20-city instance with seed 2 the run ends at length 367.5 while the best tour seen was 364.4. Keep a separate best copy and return it.

  • Forgetting to undo a rejected swap

    If a rejected proposal stays in the order array, the tour drifts while the stored energy does not. On the 9-city input the reported length is 27.060 but the returned order is really 44.600 long. The page’s test that the reported length matches the tour catches exactly this.

  • Flipping the sign in the exponent

    Writing exp(+delta / temp) makes bigger damage more likely to be accepted, and as T shrinks the exponent grows until Python raises OverflowError: math range error. Run on the 9-city input with seed = 1 it did exactly that. The rule is exp(−delta / temp).

  • Starting too cold or cooling too fast

    With t0 = 0.01 the starting temperature is far below a typical step, so no worse move is ever taken: on four of five seeds the 20-city result was identical to the frozen run (417.4, 464.8, 434.6, 442.3). Cooling at alpha = 0.99 gave 424.2 on seed 1 against 368.0 for the default.

  • Judging by one lucky run

    The 20-city results above ranged from 364.4 to 432.2 across five seeds. Seed it for reproducibility, but compare settings over several seeds before deciding one is better.

Where this shows up

  • Routing and scheduling

    Delivery routes, timetables and shift rosters have far too many arrangements to enumerate and tolerate a near-optimal answer. Annealing needs only a way to score a plan and a small change that gives a neighbouring plan, which makes it easy to bolt onto a messy real-world cost function.

  • Placement and layout

    Arranging components on a chip or a floor plan so that wire length or congestion is small is a classic use: the move is “swap or shift one block”, the cost is the total wire length, and the cooling schedule controls how much rearrangement is tolerated.

  • Tuning without gradients

    When a parameter set can be scored but not differentiated, such as a rule-based system with discrete knobs, annealing can search it. It sits between hill climbing, which gets stuck, and an exhaustive grid, which does not scale.

  • The physics behind the rule

    The accept-with-probability-e^(−Δ/T) step is the Metropolis rule from statistical physics. The algorithm borrows its name from annealing metal: cool slowly and the atoms settle into a low-energy arrangement, cool fast and defects freeze in.

SOLVE IT YOURSELF

Solve it: escape a local minimum on purpose

Hill climbing walks downhill and stops at the first valley — usually the wrong one. Annealing adds one strange rule: sometimes accept a worse move, often while hot and almost never once cold. That single concession is what gets you out of the valley. Python or TypeScript.

YOUR TASK

Implement anneal(cities, seed) for a small travelling-salesman tour: start from any order, propose a 2-swap, accept it by the temperature rule, cool, repeat. Return the best tour found and its length.

HINTS — 8 IDEAS
  1. The energy is whatever you are minimising — here, total tour length. A proposal is a tiny random change: swap two cities.
  2. If a proposal improves the energy, always take it. That much is plain hill climbing.
  3. If it makes things worse, take it anyway with probability exp(-Δ/T). Large damage and low temperature both push that toward zero.
  4. So the same bad move is likely early and almost impossible late. Early on you are exploring; later you are polishing.
  5. Cool geometrically — T ← T × α with α just under 1. Cooling too fast is just hill climbing with extra steps; too slow wastes the whole budget wandering.
  6. Keep a separate record of the best tour ever seen. The current tour is allowed to get worse, so the final state is not necessarily your answer.
  7. Use a seeded generator, not the system random. Otherwise the result changes every run and you can neither test nor debug it.
  8. Nothing here proves optimality. Annealing buys a good answer to a problem where the optimum is unaffordable — and on 9 cities you can check it against brute force, which is exactly what the tests do.
CPython · WebAssembly

Keep going

Finished this one? 0 / 99 Algorithms done

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms