再写一个遗传算法简单c语言代码
时间: 2024-09-18 14:10:56 浏览: 39
遗传算法是一种模拟自然选择过程的优化搜索算法,通常用于解决复杂问题的全局最优解。以下是一个简单的C语言版遗传算法示例,用于求解最小化函数`f(x) = x^2`的问题:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 模拟个体结构
typedef struct {
double chromosome[50]; // 假设我们有50维的解空间
} Individual;
// 函数适应度评估
double fitness(Individual ind) {
return ind.chromosome[0] * ind.chromosome[0];
}
// 交叉操作
Individual crossover(Individual parent1, Individual parent2) {
int cross_point = rand() % (sizeof(individual.chromosome) - 1);
Individual child;
for (int i = 0; i < sizeof(child.chromosome); ++i) {
if (i <= cross_point)
child.chromosome[i] = parent1.chromosome[i];
else
child.chromosome[i] = parent2.chromosome[i];
}
return child;
}
// 变异操作
void mutate(Individual &ind) {
for (int i = 0; i < sizeof(ind.chromosome); ++i) {
ind.chromosome[i] += ((double)rand() / RAND_MAX) * 2 - 1; // 随机变异
}
}
// 主遗传算法循环
void genetic_algorithm(int generations, Individual population[], int size) {
srand(time(NULL)); // 设置随机种子
// 初始化种群
for (int i = 0; i < size; ++i) {
for (int j = 0; j < sizeof(population[i].chromosome); ++j) {
population[i].chromosome[j] = rand() / RAND_MAX; // 随机生成初始值
}
}
for (int gen = 0; gen < generations; ++gen) {
// 选择
double* fitness_values = new double[size];
for (int i = 0; i < size; ++i) {
fitness_values[i] = fitness(population[i]);
}
sort(fitness_values, fitness_values + size);
Individual elite = population[fitness_values[0]];
// 交叉和变异
for (int i = 1; i < size; ++i) {
Individual parent1 = population[rand() % size];
Individual parent2 = population[rand() % size];
Individual child = crossover(parent1, parent2);
mutate(child);
population[i] = child;
}
// 更新精英
population[0] = elite;
printf("Generation %d: Best fitness = %.2lf\n", gen+1, fitness(elite));
}
}
int main() {
const int population_size = 50;
const int generations = 100;
Individual* population = (Individual*)malloc(sizeof(Individual) * population_size);
genetic_algorithm(generations, population, population_size);
free(population);
return 0;
}
```
这个程序创建了一个种群,通过交叉、变异等步骤进行迭代,寻找适应度函数`x^2`的最小值。注意这只是一个简化的例子,实际应用中可能需要更复杂的编码和问题特定的适应度函数。
阅读全文