-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimulated_annealing.cpp
More file actions
96 lines (75 loc) · 1.5 KB
/
simulated_annealing.cpp
File metadata and controls
96 lines (75 loc) · 1.5 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <random>
#include <iostream>
#include <cmath>
#define PI 3.14159265358979323846
#define TMAX 1.0
#define DELTA 0.0001
//using namespace std;
std::random_device rd;
std::mt19937 gen(rd());
double test_fun(double x)
{
return (x+(1/pow(x,2)));
}
double norm_dist(double median, double std_dev)
{
std::normal_distribution<double> normal_dist(median, std_dev);
return normal_dist(gen);
}
double neighbour(double x, double t, double a, double b)
{
double x1;
x1=norm_dist(x, t);
if(x1<a)
{
return a;
}
else if(x1>b)
{
return b;
}
else
{
return x1;
}
}
double start_point(double a, double b)
{
std::uniform_real_distribution<> dist_ab(a,b);
return dist_ab(gen);
}
double random01()
{
std::uniform_real_distribution<> dist(0,1);
return dist(gen);
}
double simulated_annealing(double (*func)(double), double tmax, double delta, double a=0, double b=1)
{
double t,diff,x,x1;
t=tmax;
x=start_point(a,b);
while(t>0.0001)
{
x1=neighbour(x,t,a,b);
diff=func(x1)-func(x);
if(diff<0)
{
x=x1;
}
else
{
if(exp(-diff/t)>random01())
{
x=x1;
}
}
t=t-delta*t;
}
return x;
}
int main()
{
std::cout<<"Starting point: "<<start_point(0, 2) << std::endl;
std::cout<<"Minimum: "<<simulated_annealing(&test_fun, TMAX, DELTA, 0, 2) << std::endl;
return 0;
}