用遗传算法求解下面函数的最大值约为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 12:06:00 浏览: 85
以下是用遗传算法求解该函数最大值的Python代码:
```python
import math
import random
# 定义函数
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 + 10**(-15)))
# 定义遗传算法参数
POP_SIZE = 100 # 种群大小
GENERATIONS = 100 # 迭代次数
MUTATION_RATE = 0.01 # 突变率
# 定义种群类
class Population:
def __init__(self, pop_size):
self.pop_size = pop_size
self.population = []
for i in range(pop_size):
x = random.uniform(-1, 1)
y = random.uniform(-1, 1)
self.population.append((x, y))
def fitness(self):
fitness_values = []
for i in range(self.pop_size):
fitness_values.append(f(self.population[i][0], self.population[i][1]))
return fitness_values
def select(self, fitness_values):
max_fitness = max(fitness_values)
fitness_sum = sum(fitness_values)
if fitness_sum == 0:
return self.population[random.randint(0, self.pop_size-1)]
probabilities = [fitness_values[i] / fitness_sum for i in range(self.pop_size)]
cum_probs = [sum(probabilities[:i+1]) for i in range(self.pop_size)]
r = random.uniform(0, 1)
for i in range(self.pop_size):
if r <= cum_probs[i]:
return self.population[i]
def crossover(self, parent1, parent2):
x1, y1 = parent1
x2, y2 = parent2
child1 = (x1, y2)
child2 = (x2, y1)
return child1, child2
def mutate(self, child):
x, y = child
if random.random() < MUTATION_RATE:
x = random.uniform(-1, 1)
if random.random() < MUTATION_RATE:
y = random.uniform(-1, 1)
return (x, y)
def next_generation(self):
fitness_values = self.fitness()
new_population = []
for i in range(self.pop_size//2):
parent1 = self.select(fitness_values)
parent2 = self.select(fitness_values)
child1, child2 = self.crossover(parent1, parent2)
child1 = self.mutate(child1)
child2 = self.mutate(child2)
new_population.extend([child1, child2])
self.population = new_population
# 运行遗传算法
population = Population(POP_SIZE)
for i in range(GENERATIONS):
print("Generation:", i+1)
fitness_values = population.fitness()
max_fitness = max(fitness_values)
max_index = fitness_values.index(max_fitness)
print("Max fitness:", max_fitness)
print("Best solution:", population.population[max_index])
population.next_generation()
```
该代码会输出每一代的最大适应度和最佳解,最后输出的最佳解即为所求的函数最大值。
阅读全文