AI Wiki中文/EN

Simulated annealing

模拟退火

Accept uphill moves, separate equilibrium from cooling, and test what a finite annealing run actually guarantees.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Allow a bad step so that a better place stays reachable

Imagine thirteen positions in a line, with costs 6,4,2,3,5,8,9,6,3,1,0,2,3. Start at position 2, whose cost is 2. Both immediate neighbors cost more, so strict greedy descent stops. Yet position 10 has cost 0. Every route along this line to that better valley must first cross position 6 at cost 9.

Simulated annealing sometimes accepts a cost increase. Early in a run it may accept many such moves; as its temperature falls, increases become harder to accept. Temperature is an algorithm parameter, measured in the same units as the cost. It does not mean that a computer is physically heating up.

Kirkpatrick, Gelatt and Vecchi’s 1983 paper develops this connection between statistical-mechanics sampling and combinatorial optimization. It discusses electronic-system partitioning, placement and wiring. Our thirteen-position example is an original teaching model, not a reproduction of those engineering experiments. Optimization by Simulated Annealing, pp.671–673

Reaching a lower valley requires a rise of 7

0369E+70123456789101112StartMinimumx

Scroll sideways for the full plot; arrow keys work when focused.

For the next move 2 → 3, cost rises by 1. Acceptance probabilities at different temperatures:

T = 477.9%
T = 136.8%
T = 0.251.8%
Dots are legal states; lines connect neighbors. The probabilities concern one proposed rise of 1, not crossing the whole barrier or finding the optimum.

The local valley costs 2 and the intervening peak costs 9, giving a barrier of 7. That barrier is different from the next step’s cost increase: the move 2→3 rises by only 1. Confusing those two quantities makes both acceptance probabilities and cooling arguments misleading.

One acceptance rule, two different time scales

We minimize a cost E(x)E(x). At state xx, randomly propose a neighbor yy and compute Δ=E(y)−E(x)\Delta=E(y)-E(x). With positive temperature TT, the Metropolis acceptance rule is

aT(x,y)=min⁡{1,exp⁡(−Δ/T)}.a_T(x,y)=\min\{1,\exp(-\Delta/T)\}.

An improvement or equal-cost move is accepted. A worse move is accepted with probability exp⁡(−Δ/T)\exp(-\Delta/T); rejection leaves the current state unchanged. For an increase of 2, temperature 2 gives e−1≈0.3679e^{-1}\approx0.3679, while temperature 0.5 gives e−4≈0.0183e^{-4}\approx0.0183. The 1983 paper describes this rule and treats a cooling schedule as both the chosen temperatures and the work spent at each one. Kirkpatrick and colleagues, pp.672–673

Why this exponential? For a fixed temperature and symmetric proposal probabilities q(x,y)=q(y,x)q(x,y)=q(y,x) on a finite state space, consider the distribution

πT(x)=exp⁡(−E(x)/T)ZT,ZT=∑zexp⁡(−E(z)/T).\pi_T(x)=\frac{\exp(-E(x)/T)}{Z_T},\qquad Z_T=\sum_z\exp(-E(z)/T).

The flow from xx to yy under this distribution equals the reverse flow:

πT(x)q(x,y)aT(x,y)=q(x,y)ZTmin⁡{e−E(x)/T,e−E(y)/T}.\pi_T(x)q(x,y)a_T(x,y)=\frac{q(x,y)}{Z_T}\min\{e^{-E(x)/T},e^{-E(y)/T}\}.

The right side is unchanged when xx and yy are exchanged. This is detailed balance, which establishes stationarity. If every state can reach every other (irreducibility), and return times are not restricted to multiples of a common integer greater than 1 (aperiodicity), running long enough at that fixed temperature approaches this distribution. Its weight favors low costs. That does not establish that a short run has mixed, or that a chain whose temperature keeps changing is in equilibrium. Hajek’s introductory discussion separates fixed-temperature equilibrium from the cooling process. Cooling Schedules for Optimal Annealing, pp.311–313

Our proposal chooses left or right with equal probability and stays put if it tries to leave the line. Thus neighboring positions propose each other with probability one-half, including at the boundaries. Choosing uniformly only among valid neighbors would be different: an endpoint would always propose inward, while the reverse proposal would have probability one-half. The uncorrected rule would then favor states according to proposal degree as well as energy; the pure Boltzmann expression above would not describe its stationary distribution.

Keep the best state separately from the current state

This complete Python program fixes a finite line neighborhood and uses a private seeded random generator. It accepts finite numeric energies whose differences remain finite after conversion to floats. Index, step count and seed must be integers; booleans are rejected. Temperature must be positive, the cooling multiplier lies in (0,1], and a positive temperature floor prevents the schedule from underflowing to zero.

Each iteration attempts one move, including rejected and boundary moves. A trace row contains current index, current cost, best cost so far and the temperature used. The initial row precedes all attempts. Returning the best state matters because an accepted uphill move can leave the final state worse than one already visited. The function stops at its attempt budget; it does not certify a global optimum.

from math import exp, isfinite
from random import Random


def finite_number(value):
    if type(value) not in (int, float):
        raise ValueError('expected a finite real number')
    try:
        number = float(value)
    except OverflowError as error:
        raise ValueError('number is outside the float range') from error
    if not isfinite(number):
        raise ValueError('expected a finite real number')
    return number


def acceptance(delta, temperature):
    delta, temperature = finite_number(delta), finite_number(temperature)
    if temperature <= 0:
        raise ValueError('temperature must be positive')
    return 1.0 if delta <= 0 else exp(-delta / temperature)


def anneal(energies, start, steps=400, temperature=8.0,
           cooling=0.98, minimum_temperature=0.001, seed=7):
    energies = tuple(finite_number(e) for e in energies)
    if not energies or not isfinite(max(energies)-min(energies)):
        raise ValueError('need a nonempty landscape with finite energy differences')
    if type(start) is not int or not 0 <= start < len(energies):
        raise ValueError('start must be a valid integer index')
    if type(steps) is not int or steps < 0 or type(seed) is not int:
        raise ValueError('steps must be nonnegative; steps and seed must be integers')
    temperature = finite_number(temperature)
    cooling = finite_number(cooling)
    minimum_temperature = finite_number(minimum_temperature)
    if not 0 < minimum_temperature <= temperature or not 0 < cooling <= 1:
        raise ValueError('need 0 < minimum_temperature <= temperature and 0 < cooling <= 1')
    rng = Random(seed)
    current = best = start
    trace = [(current, energies[current], energies[best], temperature)]
    for _ in range(steps):
        # A blocked left/right proposal stays put; the proposal is symmetric.
        step = rng.choice((-1, 1))
        candidate = min(len(energies)-1, max(0, current+step))
        delta = energies[candidate]-energies[current]
        if delta <= 0 or rng.random() < acceptance(delta, temperature):
            current = candidate
        if energies[current] < energies[best]:
            best = current
        trace.append((current, energies[current], energies[best], temperature))
        temperature = max(minimum_temperature, temperature*cooling)
    return {'state': current, 'best': best, 'trace': trace}


ENERGIES = (6, 4, 2, 3, 5, 8, 9, 6, 3, 1, 0, 2, 3)
result = anneal(ENERGIES, 2)
assert result == anneal(ENERGIES, 2)
assert len(result['trace']) == 401
assert ENERGIES[result['best']] <= ENERGIES[result['state']]
assert abs(acceptance(2, 2)-exp(-1)) < 1e-15
print('final index:', result['state'], 'best index:', result['best'])
print('best cost:', ENERGIES[result['best']])

With the shown parameters on Python 3.12.4, seed 7 visits position 10 and returns it as both final and best state. The trace contains 37 accepted cost increases before settling there. By contrast, with constant temperature 8, seed 0 visits the optimum but ends at position 11, whose cost is 2. Keeping only the final state would throw away a better answer.

For NN input energies and KK attempts, this line model uses O(N+K)O(N+K) time and storage: input conversion and each attempt are constant work per item, and the full trace retains K+1K+1 rows. Without a trace, additional search state is constant-size after the energy array is stored. In a routing or scheduling application, generating a neighbor and evaluating its cost can dominate the runtime; they are not constant merely because this toy array lookup is.

Cooling slowly is a condition, not a finish time

On this line, the only nonglobal local minimum is position 2. Reaching any strictly cheaper state requires crossing cost 9, so its depth is d∗=9−2=7d^*=9-2=7. Hajek’s finite-state result assumes irreducibility, weak reversibility and a positive nonincreasing temperature tending to zero. Weak reversibility means that below any cost ceiling, reachability works in both directions; our symmetric line satisfies it. Under those conditions, convergence in probability to the set of global minima is characterized by

∑k=1∞exp⁡(−d∗/Tk)=∞.\sum_{k=1}^{\infty}\exp(-d^*/T_k)=\infty.

For Tk=c/log⁡(k+1)T_k=c/\log(k+1), the terms become (k+1)−d∗/c(k+1)^{-d^*/c}. The series diverges when c≥d∗c\ge d^*, including equality. This is an asymptotic statement about the current state, not a finite-budget guarantee or a practical estimate of the time needed. The paper’s Theorem 1 and accompanying remark state these conditions. Hajek, pp.313–314, Theorem 1

Our geometric schedule with a positive floor does not satisfy the theorem’s limit-to-zero condition. It is an explicitly bounded experiment. A geometric schedule without that floor can cool too quickly for the barrier condition. Nor does a very small fixed temperature solve the mixing problem: at low temperature, an uphill escape may be so rare that the run spends its entire budget in the first valley.

In floating-point computation, a very small acceptance probability can underflow to zero. Then a theoretically possible transition is impossible in that implementation. The floor prevents a zero denominator but cannot guarantee adequate exploration. Wider neighborhoods, restarts and different schedules change the experiment and should be compared under a defined evaluation budget.

Measure visits, final states and the proposal rule

We ran the same landscape from position 2 for 400 attempts per run, using seeds 0 through 99 and initial temperature 8. The floor was 0.001. These are observed counts from the supplied Python implementation, not estimated universal success rates:

MultiplierBest cost 0Final cost 0
0.905/1005/100
0.9833/10031/100
1.0098/10015/100

“Best cost 0” means that a zero-cost state was visited; “Final cost 0” means the last state had that cost. Constant high temperature explores broadly in this small example but often leaves the optimum. The numbers depend on the landscape, budget, proposal, seed set and floating-point behavior. The code never uses the known minimum to decide a move; exhaustive inspection is used only to evaluate it afterward.

The independent checks form explicit transition matrices for small fixed-temperature lines and verify row sums, detailed balance and the stationary distribution. They also construct the unequal-degree proposal counterexample, verify the barrier, and check every recorded best cost against the minimum cost actually visited.

1. A proposal raises cost by 2 at temperature 2. What is accepted, and what is returned after rejection?

Answer: Accept with probability exp(−1), about 0.3679. If rejected, retain the current state for the next iteration. The cost 2 rise is not an instruction to add 2 to the temperature.

2. Change costs from minutes to seconds. How should temperature change?

Answer: Multiply it by 60, including the initial temperature and floor, to preserve the ratio of cost difference to temperature. Adding the same constant to every cost changes no cost difference and needs no temperature change.

3. Does the constant-temperature row prove that a higher temperature is always better?

Answer: No. It visits the optimum more often in this finite example but finishes there much less often than the 0.98 row. Different landscapes or proposals can change both outcomes. Specify whether the task returns the current or best-visited state.

4. A run has made no accepted uphill move for 100 attempts. Is its current state globally optimal?

Answer: No. The temperature may be too low, the proposals may be unhelpful, or the random draws may have rejected all escapes. Lack of improvement within a budget is not a proof over the whole state space.

Sampling ideas used for optimization

At fixed temperature, the acceptance rule defines a sampling process under the stated proposal assumptions. Annealing changes temperature to favor lower costs over time. Keeping the best visited state adds an optimization record; it does not turn those recorded best states into samples from the Boltzmann distribution.

The 1983 paper explains the physical analogy and engineering examples; the 1988 paper studies precise cooling conditions. Their claims address different questions. For the simpler rule that never accepts a worse neighbor, read hill climbing. For choosing states, neighborhoods and cost evaluations, read local search. These design choices determine whether an escape move is even available before any temperature is selected.

Make a prediction, then check

Annealing leaves the best point it visited before the run ends. How should the program preserve that answer?

Choose one answer

Learning objectives

  • Distinguish single-move acceptance, fixed-temperature equilibrium and cooling; check boundary proposals.
  • Track current and best states separately, calculate barriers and state the limits of finite budgets and convergence conditions.

Prerequisites & connections

Explore related knowledge →

References

  1. Optimization by Simulated Annealing
    S. Kirkpatrick; C. D. Gelatt, Jr.; M. P. Vecchi · 1983
  2. Cooling Schedules for Optimal Annealing
    Bruce Hajek · 1988

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check:primary-source locations,original executable examples,independent finite-state oracles,bilingual review and a second Codex agent cross-check;not independent human peer review.

  • Root reread bilingual acceptance, detailed balance, symmetric boundaries, barrier7, Hajek conditions, input contracts, budgets and trace storage.
  • Another Codex agent independently reran300full trajectories using log acceptance and checked printed formulas; results matched with no substantive issue. Revised test-matrix wording to explicit rather than exact arithmetic and fixed English number spacing.
  • Six independent tests cover stationary flows, degree bias, acceptance/scaling/underflow, minimax-Floyd barriers,300-run table, every running minimum, budgets and invalid inputs.
  • Paired code,display formulas and main anchors match. All48search checks and101article Python programs passed. Reviews are AI technical checks,not independent human peer review.
  • Reread display wording: added English number spacing and made zero-cost table labels distinct from position0. Example code,display formulas and experiment values are unchanged.
  • Added visible mobile sideways-scroll/arrow-key guidance because the narrow plot shows only part of the line. Data,calculations and coordinates are unchanged; bilingual guidance reread.

Source locations checked:

  • Optimization by Simulated Annealing · Read printed671–673, PDF2–4 after archive cover: iterative improvement and restarts; Metropolis sign, uniform-draw acceptance; effective T has cost units; schedule includes work at each temperature. Only small original line experiment implemented.
  • Cooling Schedules for Optimal Annealing · Read printed311–315; visually inspected311 and314. Confirmed finite irreducible/weakly reversible assumptions, positive nonincreasing T→0, sum exp(-d*/T_k) divergence, T_k=c/log(k+1) iff c≥d*. Intro312 separates proposal stationary weights from pure Boltzmann. No full theorem proof reproduced.

Related topics

No matches. Try a synonym or acronym.

0 results shown

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