遗传算法 (1)函数优化问题为例,求f(x)=x^2的最大值,其中x∈[0,31]; (2)假设适应度函数为f(x),至于种群规模、选择算法、交叉概率、变异概率和计算精度等自行确定。 提供一份C语言代码谢谢
时间: 2024-12-25 22:26:37 浏览: 16
遗传算法通常用于解决复杂的全局优化问题,包括函数优化。以下是使用遗传算法寻找函数f(x) = x^2在给定区间[x=0, x=31]上的最大值的一个简化示例。请注意,这个例子仅作展示遗传算法的基本思想,实际应用可能需要更复杂的设计和优化。
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// 定义适应度函数
double fitness(double *individual, int size) {
return -pow(individual[size - 1], 2); // 对于最大化,我们取负值,因为默认的maximization是正向的
}
// 生成随机个体
void generate_individual(double *population, int size, double min, double max) {
for (int i = 0; i < size; i++) {
population[i] = (double)rand() / RAND_MAX * (max - min) + min;
}
}
// 进行选择操作
double* selection(double *population, int size, int elitism) {
double *elite = &population[elitism];
double *best = elite;
double best_fitness = fitness(elite, elitism);
for (int i = elitism + 1; i < size; i++) {
double current_fitness = fitness(&population[i], 1);
if (current_fitness > best_fitness) {
best = &population[i];
best_fitness = current_fitness;
}
}
return best;
}
// 主遗传算法循环
double genetic_algorithm(int generations, int population_size, double min, double max, double crossover_rate, double mutation_rate) {
double *population = malloc(population_size * sizeof(double));
generate_individual(population, population_size, min, max);
for (int gen = 0; gen < generations; gen++) {
printf("Generation %d: Max fitness = %.2f\n", gen, -fitness(&population[0], 1)); // 因为最大化,打印的是负值
// 基因交叉
for (int i = 0; i < population_size - 1; i += 2) {
if (rand() < crossover_rate) {
double* parent1 = selection(population, population_size, 1);
double* parent2 = selection(population, population_size, 1);
double* offspring1 = &population[i];
double* offspring2 = &population[i + 1];
for (int j = 0; j < population_size - 1; j++) {
offspring1[j] = parent1[j] + rand() / RAND_MAX * (parent2[j] - parent1[j]);
offspring2[j] = parent2[j] + rand() / RAND_MAX * (parent1[j] - parent2[j]);
}
}
// 基因变异
for (int i = 0; i < population_size; i++) {
if (rand() < mutation_rate) {
population[i] += rand() / RAND_MAX * (max - min);
}
}
}
free(population);
return population[0]; // 返回最佳解
}
int main() {
const int generations = 100;
const int population_size = 50;
const double min = 0.0;
const double max = 31.0;
const double crossover_rate = 0.8;
const double mutation_rate = 0.01;
double max_value = genetic_algorithm(generations, population_size, min, max, crossover_rate, mutation_rate);
printf("Maximized value of f(x) = x^2 is %.2f at x ≈ %.2f\n", -max_value, sqrt(-max_value));
return 0;
}
```
阅读全文