Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Simulated Annealing in C#
The simulated annealing is a metaheuristic, a random search algorithm inspired from physics sciences. In this example, we will doing a simple thing : adjusting one coefficent for having a better results for the algorithm to found the global minimum of the function :
f(X)=0.11(0.5 X² + Cos[Pi X] - 2 Sin[2 Pi X] + Cos[3 Pi X]*Sin[Pi X] in [-5; 5].
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimulatedAnnealing
{
class Program
{
static Random rand = new Random();
static int ct0, ct1, ct2, ct3;
static double random_x(double xmin, double xmax)
{
return xmin + (xmax - xmin) * rand.NextDouble();
}
static double random_variate(double x, double xmin, double xmax, double delta)
{
var x0 = x - delta < xmin ? xmin : x - delta;
var x1 = x + delta > xmax ? xmax : x + delta;
return random_x(x0, x1);
}
static double energy(double x)
{
return COEF * myFunction(x);
}
static double acceptanceProbability(double energy, double new_energy, double temp)
{
if (new_energy < energy)
{
ct1++;
return 1.0;
}
return Math.Exp((energy - new_energy) / temp);
}
static int COEF = 100;
static double simulated_annealing()
{
double XMIN = -5;
double XMAX = 5;
double Temperature = 1000;
double minTemp = 1;
Press desired key combination and then press ENTER.
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content