遗传算法求函数最大值python代码
时间: 2024-05-22 10:08:52 浏览: 123
遗传算法算函数最大值
遗传算法是一种常用的优化算法,它可以用来求解函数最大值问题。下面是一个简单的Python实现:
```python
import random
# 遗传算法求函数最大值
# 目标函数:f(x) = x * sin(10 * pi * x) + 2.0
# 取值范围:-1 <= x <= 2
def fitness(x):
return x * math.sin(10 * math.pi * x) + 2.0
def selection(population, fitness):
# 选择算子,采用轮盘赌选择
total_fitness = sum(fitness)
r = random.uniform(0, total_fitness)
for i, f in enumerate(fitness):
r -= f
if r <= 0:
return population[i]
def crossover(parent1, parent2):
# 交叉算子,采用单点交叉
pos = random.randint(0, len(parent1) - 1)
child1 = parent1[:pos] + parent2[pos:]
child2 = parent2[:pos] + parent1[pos:]
return child1, child2
def mutation(child, mutation_rate):
# 变异算子,采用随机突变
for i in range(len(child)):
if random.random() < mutation_rate:
child[i] = random.uniform(-1, 2)
return child
# 参数设置
pop_size = 50 # 种群大小
gen_size = 100 # 迭代次数
mutation_rate = 0.01 # 变异概率
# 初始化种群
population = []
for i in range(pop_size):
individual = [random.uniform(-1, 2) for j in range(10)]
population.append(individual)
# 进化
for gen in range(gen_size):
# 计算适应度
fitness_list = [fitness(individual) for individual in population]
# 选择
new_population = []
for i in range(pop_size):
parent1 = selection(population, fitness_list)
parent2 = selection(population, fitness_list)
child1, child2 = crossover(parent1, parent2)
child1 = mutation(child1, mutation_rate)
child2 = mutation(child2, mutation_rate)
new_population.append(child1)
new_population.append(child2)
population = new_population
# 找出最佳个体
best_individual = max(population, key=fitness)
best_fitness = fitness(best_individual)
print('best individual:', best_individual)
print('best fitness:', best_fitness)
```
阅读全文