用C++写一个遗传算法
时间: 2023-07-07 16:25:25 浏览: 105
好的,以下是一个简单的C++遗传算法实现示例:
```cpp
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
// 定义目标函数
double targetFunc(double x) {
return x * x;
}
// 遗传算法类
class GeneticAlgorithm {
public:
GeneticAlgorithm(int p, double mr, double cr, double a, double b) :
populationSize(p), mutationRate(mr), crossoverRate(cr), lowerBound(a), upperBound(b) {}
void run(int maxGeneration);
private:
int populationSize; // 种群大小
double mutationRate; // 变异率
double crossoverRate; // 交叉率
double lowerBound; // 变量下界
double upperBound; // 变量上界
vector<double> population; // 种群
vector<double> fitness; // 种群适应度
void initialize(); // 初始化种群
void evaluate(); // 计算种群适应度
int select(); // 选择
void crossover(int p1, int p2); // 交叉
void mutate(int i); // 变异
double random(double a, double b); // 生成随机数
};
// 初始化种群
void GeneticAlgorithm::initialize() {
population.resize(populationSize);
for (int i = 0; i < populationSize; i++) {
population[i] = random(lowerBound, upperBound);
}
}
// 计算种群适应度
void GeneticAlgorithm::evaluate() {
fitness.resize(populationSize);
for (int i = 0; i < populationSize; i++) {
fitness[i] = targetFunc(population[i]);
}
}
// 选择
int GeneticAlgorithm::select() {
double sum = 0;
for (int i = 0; i < populationSize; i++) {
sum += fitness[i];
}
double r = random(0, sum);
double s = 0;
for (int i = 0; i < populationSize; i++) {
s += fitness[i];
if (s > r) {
return i;
}
}
return populationSize - 1;
}
// 交叉
void GeneticAlgorithm::crossover(int p1, int p2) {
double r = random(0, 1);
if (r < crossoverRate) {
double x1 = population[p1];
double x2 = population[p2];
double alpha = random(0, 1);
population[p1] = alpha * x1 + (1 - alpha) * x2;
population[p2] = alpha * x2 + (1 - alpha) * x1;
}
}
// 变异
void GeneticAlgorithm::mutate(int i) {
double r = random(0, 1);
if (r < mutationRate) {
population[i] = random(lowerBound, upperBound);
}
}
// 生成随机数
double GeneticAlgorithm::random(double a, double b) {
return a + (b - a) * rand() / RAND_MAX;
}
// 运行遗传算法
void GeneticAlgorithm::run(int maxGeneration) {
srand((unsigned)time(NULL));
initialize();
evaluate();
int generation = 0;
while (generation < maxGeneration) {
int p1 = select();
int p2 = select();
crossover(p1, p2);
mutate(p1);
mutate(p2);
evaluate();
generation++;
}
int bestIndex = 0;
double bestFitness = fitness[0];
for (int i = 1; i < populationSize; i++) {
if (fitness[i] < bestFitness) {
bestIndex = i;
bestFitness = fitness[i];
}
}
cout << "最优解为:" << population[bestIndex] << endl;
cout << "最优值为:" << bestFitness << endl;
}
int main() {
GeneticAlgorithm ga(100, 0.01, 0.8, -5, 5); // 初始化遗传算法
ga.run(100); // 运行遗传算法
return 0;
}
```
在上面的代码中,我们首先定义了目标函数targetFunc,这是我们要优化的目标函数。然后定义了遗传算法类GeneticAlgorithm,其中包括了初始化种群、计算种群适应度、选择、交叉、变异等操作。最后,在main函数中初始化遗传算法,并运行它。
需要注意的是,这只是一个简单的示例,实际上,遗传算法的实现还需要考虑许多因素,例如选择、交叉和变异的具体方式、选择的策略等。
阅读全文