禁忌搜索算法基本原理不再赘述,请参考其它文章,本文基于c++提供一种求解多维函数极值的例子。
目标函数为Ackley函数,以二维为例两变量变化区间均为[-10,10],可自行修改变量个数及取值范围
详细代码如下:
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <vector>
using namespace std;
const int MAX_ITERATIONS = 1000000; // 最大迭代次数
const int TABU_TENURE = 10; // 禁忌长度
const int NEIGHBORHOOD_SIZE = 50; // 邻域大小
// Ackley函数
double ackley(double x, double y) {
double a = 20.0;
double b = 0.2;
double c = 2.0 * M_PI;
double term1 = -a * exp(-b * sqrt(0.5 * (x * x + y * y)));
double term2 = -exp(0.5 * (cos(c * x) + cos(c * y)));
double result = term1 + term2 + a + exp(1.0);
return result;
}
// 表示一个点
struct Point {
double x, y;
Point(double x, double y) : x(x), y(y) {}
};
// 获取邻居节点的函数
double getNeighborValue(Point point, int index) {
double oldValue, newValue;
// 如果是0,则表示x坐标;否则,表示y坐标
if (index == 0) {
oldValue = point.x;
newValue = (double)rand() / RAND_MAX * 20.0 - 10.0; // 生成-10到10之间的随机数
point.x = newValue;
}
else {
oldValue = point.y;
newValue = (double)rand() / RAND_MAX * 20.0 - 10.0; // 生成-10到10之间的随机数
point.y = newValue;
}
double result = ackley(point.x, point.y);
// 还原节点的坐标值
if (index == 0) {
point.x = oldValue;
}
else {
point.y = oldValue;
}
return result;
}
// 获取当前节点的最佳邻居节点
Point getBestNeighbor(Point current, vector<Point> tabuList) {
Point bestNeighbor = current;
double bestValue = ackley(current.x, current.y);
for (int i = 0; i < NEIGHBORHOOD_SIZE; i++) {
Point neighbor(current.x, current.y);
double neighborValue;
int j = 0;
// 如果邻居节点已经在禁忌列表中,就不考虑该节点
// 同时,如果重复了50次,也不考虑该节点
do {
int index = rand() % 2;
neighborValue = getNeighborValue(neighbor, index);
j++;
} while (find(tabuList.begin(), tabuList.end(), neighbor) != tabuList.end() && j < 50);
if (neighborValue < bestValue) {
bestNeighbor = neighbor;
bestValue = neighborValue;
}
}
return bestNeighbor;
}
int main() {
srand(time(NULL)); //设置随机数种子
Point current((double)rand() / RAND_MAX * 20.0 - 10.0, (double)rand() / RAND_MAX * 20.0 - 10.0); //随机生成初始点
double bestValue = ackley(current.x, current.y);
Point bestSolution = current;
vector<Point> tabuList; //禁忌表
for (int i = 0; i < MAX_ITERATIONS; i++) {
Point bestNeighbor = getBestNeighbor(current, tabuList);
double bestNeighborValue = ackley(bestNeighbor.x, bestNeighbor.y);
if (bestNeighborValue < bestValue) {
bestSolution = bestNeighbor;
bestValue = bestNeighborValue;
}
current = bestNeighbor;
tabuList.push_back(current); //将当前节点加入禁忌列表
if (tabuList.size() > TABU_TENURE) {
tabuList.erase(tabuList.begin()); // 禁忌列表中只保留最新的TABU_TENURE个节点
}
}
cout << "Best solution found: (" << bestSolution.x << ", " << bestSolution.y << ")" << endl;
cout<<"Best solution is"<<ackley(bestSolution.x, bestSolution.y)<<endl; //输出最小值