人工免疫算法解决f(x,y)=(a-x)^2+b(y-x^2)^2最优解的python代码
时间: 2023-11-21 15:06:35 浏览: 78
sum_求和_
以下是使用人工免疫算法求解函数f(x,y)=(a-x)^2 b(y-x^2)^2最优解的python代码:
```
import random
import math
def calculate_fitness(x, y, a, b):
return (a - x) ** 2 + b * (y - x ** 2) ** 2
def generate_antibody():
return [random.uniform(-10.0, 10.0), random.uniform(-10.0, 10.0)]
def clone_antibody(antibody):
clone = [x + random.gauss(0.0, 0.1) for x in antibody]
return clone
def mutate_antibody(antibody, mutation_rate):
mutated_antibody = []
for x in antibody:
if random.random() < mutation_rate:
mutated_antibody.append(x + random.gauss(0.0, 1.0))
else:
mutated_antibody.append(x)
return mutated_antibody
def select_antibodies(population, selection_rate):
population_size = len(population)
num_selected = int(population_size * selection_rate)
population.sort(key=lambda x: x[1], reverse=True)
return population[:num_selected]
def generate_population(num_antibodies):
population = []
for i in range(num_antibodies):
antibody = generate_antibody()
fitness = calculate_fitness(antibody[0], antibody[1], 1, 100)
population.append((antibody, fitness))
return population
def artificial_immune_algorithm(num_antibodies, num_iterations, selection_rate, mutation_rate):
population = generate_population(num_antibodies)
for i in range(num_iterations):
clones = [clone_antibody(a) for a, _ in population]
mutated = [mutate_antibody(c, mutation_rate) for c in clones]
antibodies = population + [(m, calculate_fitness(m[0], m[1], 1, 100)) for m in mutated]
selected = select_antibodies(antibodies, selection_rate)
population = selected
print('Iteration:', i + 1, 'Best fitness:', population[0][1])
return population[0][0]
if __name__ == '__main__':
best_antibody = artificial_immune_algorithm(50, 100, 0.2, 0.1)
print('Best solution:', best_antibody)
```
请注意,此代码并不一定是最优解,因为人工免疫算法是一种随机化算法,每次运行可能会得到不同的结果。
阅读全文