人工智能实验遗传算法C++ 代码 计算适应度
时间: 2023-09-03 10:16:47 浏览: 54
以下是一个简单的遗传算法实验的C++代码,包括计算适应度的函数:
```c++
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
// 假设我们需要优化的函数为 f(x) = x^2,x∈[0,31]
double fitness(int x) {
return x * x;
}
// 随机生成初始种群
vector<int> generate_population(int size) {
vector<int> population(size);
for (int i = 0; i < size; i++) {
population[i] = rand() % 32; // 生成0-31之间的随机整数
}
return population;
}
// 选择操作,使用轮盘赌法进行选择
vector<int> selection(const vector<int>& population, int size) {
vector<int> selected(size);
double sum_fitness = 0;
for (int i = 0; i < population.size(); i++) {
sum_fitness += fitness(population[i]);
}
for (int i = 0; i < size; i++) {
double r = (double)rand() / RAND_MAX * sum_fitness;
double s = 0;
for (int j = 0; j < population.size(); j++) {
s += fitness(population[j]);
if (s >= r) {
selected[i] = population[j];
break;
}
}
}
return selected;
}
// 交叉操作,使用单点交叉
void crossover(vector<int>& population) {
for (int i = 0; i < population.size() - 1; i += 2) {
if (rand() / double(RAND_MAX) < 0.8) { // 80%的概率进行交叉
int pos = rand() % 5 + 1; // 生成一个1-5之间的随机整数,作为交叉点
int tmp = population[i] % (1 << pos);
population[i] = (population[i] >> pos << pos) + (population[i + 1] % (1 << (5 - pos)));
population[i + 1] = (population[i + 1] >> (5 - pos) << (5 - pos)) + tmp;
}
}
}
// 变异操作,使用位变异
void mutation(vector<int>& population) {
for (int i = 0; i < population.size(); i++) {
if (rand() / double(RAND_MAX) < 0.1) { // 10%的概率进行变异
int pos = rand() % 5; // 生成一个0-4之间的随机整数,作为变异位
population[i] ^= (1 << pos); // 将变异位取反
}
}
}
// 遗传算法主函数
int genetic_algorithm(int size, int max_generation) {
vector<int> population = generate_population(size); // 生成初始种群
int generation = 0;
while (generation < max_generation) {
vector<int> selected = selection(population, size / 2); // 选择
crossover(selected); // 交叉
mutation(selected); // 变异
population = selected;
generation++;
}
int best = population[0];
double best_fitness = fitness(best);
for (int i = 1; i < population.size(); i++) {
double f = fitness(population[i]);
if (f > best_fitness) {
best_fitness = f;
best = population[i];
}
}
return best;
}
int main() {
srand(time(NULL));
int best = genetic_algorithm(100, 1000);
cout << "最优解为:" << best << endl;
cout << "最优解对应的函数值为:" << fitness(best) << endl;
return 0;
}
```
在上述代码中,`fitness`函数用于计算适应度,`generate_population`函数用于随机生成初始种群,`selection`函数用于进行选择操作,`crossover`函数用于进行交叉操作,`mutation`函数用于进行变异操作,`genetic_algorithm`函数为遗传算法的主函数。在主函数中,先生成初始种群,然后进行若干代的选择、交叉、变异操作,最终得到最优解。