遗传算法C语言程序实例
时间: 2023-08-29 11:08:42 浏览: 46
以下是一个简单的遗传算法的C语言程序实例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define POP_SIZE 50 // 种群大小
#define NUM_VARS 1 // 变量个数
#define NUM_GENERATIONS 100 // 迭代次数
#define CROSSOVER_PROB 0.8 // 交叉概率
#define MUTATION_PROB 0.1 // 变异概率
// 目标函数
double func(double x) {
return 2 * sin(x) + cos(3 * x);
}
// 个体结构体
typedef struct {
double vars[NUM_VARS]; // 变量数组
double fitness; // 适应度
} Individual;
// 初始化种群
void initializePopulation(Individual population[]) {
for (int i = 0; i < POP_SIZE; i++) {
for (int j = 0; j < NUM_VARS; j++) {
population[i].vars[j] = (double)rand() / RAND_MAX * 10 - 5;
}
}
}
// 计算适应度
void calculateFitness(Individual population[]) {
for (int i = 0; i < POP_SIZE; i++) {
population[i].fitness = func(population[i].vars[0]);
}
}
// 选择
void selection(Individual population[]) {
// 排序种群
for (int i = 0; i < POP_SIZE - 1; i++) {
for (int j = 0; j < POP_SIZE - i - 1; j++) {
if (population[j].fitness > population[j+1].fitness) {
Individual temp = population[j];
population[j] = population[j+1];
population[j+1] = temp;
}
}
}
// 选择前一半个体作为父代
for (int i = 0; i < POP_SIZE / 2; i++) {
population[i + POP_SIZE / 2] = population[i];
}
}
// 交叉
void crossover(Individual parent1, Individual parent2, Individual* offspring1, Individual* offspring2) {
int point = rand() % NUM_VARS;
for (int i = 0; i < NUM_VARS; i++) {
if (i <= point) {
offspring1->vars[i] = parent1.vars[i];
offspring2->vars[i] = parent2.vars[i];
} else {
offspring1->vars[i] = parent2.vars[i];
offspring2->vars[i] = parent1.vars[i];
}
}
}
// 变异
void mutation(Individual* individual) {
int point = rand() % NUM_VARS;
individual->vars[point] += ((double)rand() / RAND_MAX) * 0.1;
}
// 更新种群
void updatePopulation(Individual population[]) {
for (int i = POP_SIZE / 2; i < POP_SIZE; i++) {
if ((double)rand() / RAND_MAX < CROSSOVER_PROB) {
int parent1Index = rand() % (POP_SIZE / 2);
int parent2Index = rand() % (POP_SIZE / 2);
crossover(population[parent1Index], population[parent2Index], &population[i], &population[i+1]);
i++;
} else {
int parentIndex = rand() % (POP_SIZE / 2);
population[i] = population[parentIndex];
mutation(&population[i]);
}
}
}
// 打印最优解
void printBestSolution(Individual population[]) {
double bestFitness = population[0].fitness;
double bestSolution = population[0].vars[0];
for (int i = 1; i < POP_SIZE; i++) {
if (population[i].fitness < bestFitness) {
bestFitness = population[i].fitness;
bestSolution = population[i].vars[0];
}
}
printf("最小值为 %f,对应的解为 %f\n", bestFitness, bestSolution);
}
int main() {
Individual population[POP_SIZE];
// 初始化种群
initializePopulation(population);
// 遗传算法迭代
for (int i = 0; i < NUM_GENERATIONS; i++) {
// 计算适应度
calculateFitness(population);
// 选择
selection(population);
// 更新种群
updatePopulation(population);
}
// 输出结果
printBestSolution(population);
return 0;
}
```
请注意,这只是一个简单的示例程序,具体的遗传算法实现可能会根据实际情况有所调整。