遗传算法求(6.452*(x+0.125*y)*(cos(x)-cos(2*y))**2)/(0.8+(x-4.2)**2+2*(y-7)**2)+3.226*y最大值与最小值的代码
时间: 2024-05-15 13:11:11 浏览: 92
遗传算法是一种基于生物进化理论的优化算法,其目的是通过模拟自然选择和遗传机制,不断地进化出更优秀的解。在求解(6.452*(x+0.125*y)*(cos(x)-cos(2*y))**2)/(0.8+(x-4.2)**2+2*(y-7)**2)+3.226*y的最大值和最小值时,我们可以使用遗传算法。
下面是使用Python实现该问题的遗传算法代码:
```python
import random
# 目标函数
def target_function(x, y):
return (6.452*(x+0.125*y)*(cos(x)-cos(2*y))**2)/(0.8+(x-4.2)**2+2*(y-7)**2)+3.226*y
# 生成初始种群
def generate_population(size):
population = []
for i in range(size):
x = random.uniform(-10, 10)
y = random.uniform(-10, 10)
population.append((x, y))
return population
# 计算适应度
def calculate_fitness(population):
fitness = []
for individual in population:
x, y = individual
fitness.append(target_function(x, y))
return fitness
# 选择
def selection(population, fitness):
new_population = []
total_fitness = sum(fitness)
for i in range(len(population)):
probability = fitness[i] / total_fitness
if random.random() < probability:
new_population.append(population[i])
return new_population
# 交叉
def crossover(population):
new_population = []
for i in range(len(population)):
parent1 = random.choice(population)
parent2 = random.choice(population)
child = (parent1, parent2)
new_population.append(child)
return new_population
# 变异
def mutation(population, probability):
new_population = []
for individual in population:
x, y = individual
if random.random() < probability:
x += random.uniform(-1, 1)
y += random.uniform(-1, 1)
new_population.append((x, y))
return new_population
# 遗传算法主函数
def genetic_algorithm(size, generations, mutation_probability):
population = generate_population(size)
for i in range(generations):
fitness = calculate_fitness(population)
population = selection(population, fitness)
population = crossover(population)
population = mutation(population, mutation_probability)
best_individual = max(population, key=lambda x: target_function(x, x))
worst_individual = min(population, key=lambda x: target_function(x, x))
return best_individual, worst_individual
# 示例运行
best_individual, worst_individual = genetic_algorithm(size=100, generations=100, mutation_probability=0.1)
print("最大值:", target_function(*best_individual))
print("最小值:", target_function(*worst_individual))
```
阅读全文