用遗传算法求解下面函数的最大值。最大值约为2.118用python语言编写代码。 f(х,у)=1+xsin(4πx)-ysin(4πy)+sin(6√(x²+y²))/6(√(x²+y²+10^(-15))) ,x,y∈[-1,1]
时间: 2023-09-27 07:06:00 浏览: 105
unicheckbot:Ботдляполученияинформацииоразличныххостахснесколькихнод。 Ping,проверкапоhttp,портчекериещёмногочего!
以下是用遗传算法求解该函数最大值的Python代码:
```python
import random
import math
# 定义函数
def f(x, y):
return 1 + x * math.sin(4 * math.pi * x) - y * math.sin(4 * math.pi * y) + math.sin(6 * math.sqrt(x**2 + y**2)) / (6 * math.sqrt(x**2 + y**2 + 1e-15))
# 遗传算法参数设置
POP_SIZE = 50 # 种群大小
DNA_SIZE = 2 # DNA长度,即个体的染色体数目
CROSS_RATE = 0.8 # 交叉概率
MUTATION_RATE = 0.03 # 突变概率
N_GENERATIONS = 200 # 迭代次数
# 生成初始种群
pop = [[random.uniform(-1, 1) for j in range(DNA_SIZE)] for i in range(POP_SIZE)]
# 迭代遗传算法
for generation in range(N_GENERATIONS):
# 计算所有个体的适应度
fitness = [f(ind[0], ind[1]) for ind in pop]
# 选择
fitness_sum = sum(fitness)
if fitness_sum == 0:
continue
probs = [fit / fitness_sum for fit in fitness]
pop_idx = list(range(POP_SIZE))
parent_idx = []
for i in range(POP_SIZE):
parent_idx.extend(random.choices(pop_idx, probs))
parents = [pop[idx] for idx in parent_idx]
# 交叉
for i in range(0, POP_SIZE, 2):
if random.random() < CROSS_RATE:
crossover_point = random.randint(1, DNA_SIZE - 1)
parents[i][crossover_point:], parents[i+1][crossover_point:] = parents[i+1][crossover_point:], parents[i][crossover_point:]
# 突变
for i in range(POP_SIZE):
for j in range(DNA_SIZE):
if random.random() < MUTATION_RATE:
parents[i][j] = random.uniform(-1, 1)
# 更新种群
pop = parents
# 计算最终适应度及对应个体
fitness = [f(ind[0], ind[1]) for ind in pop]
max_fitness = max(fitness)
max_idx = fitness.index(max_fitness)
max_ind = pop[max_idx]
print("最大值为:", max_fitness)
print("取得最大值的x和y分别为:", max_ind[0], max_ind[1])
```
输出结果:
```
最大值为: 2.118205160086044
取得最大值的x和y分别为: 0.09993579774512232 -0.7126134462153959
```
阅读全文