掌握遗传算法,学会利用遗传解决函数优化问题。 二 实验内容 用遗传算法求带根号函数的最大值。最大值约为2.118
时间: 2024-03-16 21:44:50 浏览: 64
好的,现在我们有了问题的具体描述。下面是一个使用遗传算法求解的示例代码,您可以根据需要进行修改:
```python
import random
import math
# 定义目标函数,这里使用示例函数 f(x) = x * sin(10 * pi * x) + 2.0
def target_func(x):
return x * math.sqrt(10 - x) + 2.0
# 定义遗传算法的参数
POPULATION_SIZE = 100 # 种群大小
CROSSOVER_RATE = 0.8 # 交叉概率
MUTATION_RATE = 0.05 # 变异概率
GENERATION_COUNT = 500 # 迭代次数
# 初始化种群
def init_population():
population = []
for i in range(POPULATION_SIZE):
individual = random.uniform(0, 10)
population.append(individual)
return population
# 计算适应度
def fitness(individual):
return target_func(individual)
# 进行选择
def selection(population):
fitness_values = [fitness(individual) for individual in population]
total_fitness = sum(fitness_values)
probabilities = [fitness_value / total_fitness for fitness_value in fitness_values]
selected_indexes = random.choices(range(POPULATION_SIZE), weights=probabilities, k=POPULATION_SIZE)
return [population[index] for index in selected_indexes]
# 进行交叉
def crossover(parent1, parent2):
if random.random() < CROSSOVER_RATE:
crossover_point = random.randint(0, 31)
child1 = parent1[:crossover_point] + parent2[crossover_point:]
child2 = parent2[:crossover_point] + parent1[crossover_point:]
return child1, child2
else:
return parent1, parent2
# 进行变异
def mutation(child):
mutated_child = []
for bit in child:
if random.random() < MUTATION_RATE:
mutated_bit = random.uniform(0, 10)
else:
mutated_bit = bit
mutated_child.append(mutated_bit)
return mutated_child
# 进行遗传算法求解
def genetic_algorithm():
population = init_population()
for generation in range(GENERATION_COUNT):
sorted_population = sorted(population, key=fitness, reverse=True)
best_individual = sorted_population[0]
print(f"Generation {generation}, Best individual: {best_individual}, Fitness: {fitness(best_individual)}")
selected_population = selection(population)
next_generation = []
for i in range(0, POPULATION_SIZE, 2):
parent1 = selected_population[i]
parent2 = selected_population[i+1]
child1, child2 = crossover(parent1, parent2)
next_generation.append(mutation(child1))
next_generation.append(mutation(child2))
population = next_generation
# 运行遗传算法
genetic_algorithm()
```
这里的示例函数为 $f(x) = x \sqrt{10 - x} + 2.0$,您可以将目标函数替换为您的目标函数。需要注意的是,不同的函数可能需要不同的参数设置和变异操作,您需要根据具体情况进行修改。
阅读全文