We need to optimize the global optimum of a given function on some space using only the values of the function in some points on the space.

Simulated Annealing is a probabilistic technique for approximating the global optimum of a given function.


The name and inspiration come from annealing in metallurgy, a technique involving heating and controlled cooling of a material to increase the size of its crystals and reduce their defects. Both are attributes of the material that depend on its thermodynamic free energy. Heating and cooling the material affects both the temperature and the thermodynamic free energy. The simulation of annealing can be used to find an approximation of a global minimum for a function with many variables.

Steps of the Algorithm

Step 1 Let - current iteration, - initial temperature.

Step 2 Let - some random point from our space

Step 3 Let decrease the temperature by following rule where - some constant that often is closer to 1

Step 4 Let - the next point which was obtained from previous one by some random rule. It is usually assumed that this rule works so that each subsequent approximation should not differ very much.

Step 5 Calculate , where - the function that determines the energy of the system at this point. It is supposed that energy has the minimum in desired value .

Step 6 If then the approximation found is better than it was. So accept as new started point at the next step and go to the step Step 3

Step 7 If , then we accept with the probability of . If we don’t accept , then we let . Go to the step Step 3

The algorithm can stop working according to various criteria, for example, achieving an optimal state or lowering the temperature below a predetermined level .


As it mentioned in Simulated annealing: a proof of convergence the algorithm converges almost surely to a global maximum.


A gif from Wikipedia:


In our example we solve the N queens puzzle - the problem of placing N chess queens on an N×N chessboard so that no two queens threaten each other.

The Problem

Let - the number of intersections, where - the array of placement queens at the field (the number in array means the column, the index of the number means the row).

The problem is to find where - the global minimum, that is predefined and equals to 0 (no two queens threaten each other).

In this code that means all queens are placed at the board’s diagonal . So at the begining , because every queen intersects others.


Results of applying this algorithm with to the queens puzzle for averaged by 100 runs are below:

Results of running the code for from to and measuring the time it takes to find the solution averaged by 100 runs are below:

Open In Colab