用遗传算法求f(x)=xcosx+2的最大值Python
时间: 2024-05-06 11:21:27 浏览: 221
遗传算法求最大值
可以使用遗传算法求解这个问题。遗传算法是一种基于生物进化理论的搜索算法,它通过模拟自然选择、交叉和变异等机制,不断优化解的质量,从而达到求解最优化问题的目的。以下是使用Python实现遗传算法求解f(x)=xcos(x^2)的最大值的代码示例:
```python
import random
import math
# 目标函数
def f(x):
return x * math.cos(x * x)
# 个体类
class Individual:
def __init__(self, x):
self.x = x
self.fitness = f(x)
# 计算个体适应度
def evaluate(self):
self.fitness = f(self.x)
# 基因突变
def mutate(self):
self.x += random.uniform(-0.1, 0.1)
self.evaluate()
# 交叉操作
def crossover(self, other):
x1 = self.x
x2 = other.x
self.x = 0.5 * (x1 + x2)
other.x = 0.5 * (x1 - x2)
self.evaluate()
other.evaluate()
# 种群类
class Population:
def __init__(self, size):
self.size = size
self.individuals = [Individual(random.uniform(-10, 10)) for _ in range(size)]
# 选择优秀个体
def select(self):
fitness_sum = sum(individual.fitness for individual in self.individuals)
p = [individual.fitness / fitness_sum for individual in self.individuals]
return random.choices(self.individuals, weights=p, k=2)
# 进化过程
def evolve(self):
for _ in range(self.size):
parent1, parent2 = self.select()
offspring1 = Individual(parent1.x)
offspring2 = Individual(parent2.x)
offspring1.crossover(offspring2)
offspring1.mutate()
offspring2.mutate()
if offspring1.fitness > offspring2.fitness:
self.individuals.append(offspring1)
else:
self.individuals.append(offspring2)
self.individuals.sort(key=lambda individual: individual.fitness, reverse=True)
self.individuals = self.individuals[:self.size]
# 遗传算法求解
pop_size = 100
pop = Population(pop_size)
for i in range(100):
pop.evolve()
print("Generation", i+1, ": x =", pop.individuals[0].x, ", f(x) =", pop.individuals[0].fitness)
```
注意:以上代码仅供演示遗传算法的基本实现方法,实际使用时还需要加入更多优化和调试。
阅读全文