用人工免疫算法计算f(x,y)=(a-x)^2+b(y-x^2)^2最优解的Python代码
时间: 2023-11-21 10:06:35 浏览: 95
以下是使用人工免疫算法计算f(x,y)=(a-x)^2 b(y-x^2)^2最优解的Python代码:
```python
import random
import math
# 目标函数
def f(x, y, a, b):
return (a - x) ** 2 + b * (y - x ** 2) ** 2
# 人工免疫算法
def AIS(a, b, n, m, l_bound, u_bound, max_iter, p_mutation):
# 初始化抗体群体
antibodies = []
for i in range(n):
x = random.uniform(l_bound, u_bound)
y = random.uniform(l_bound, u_bound)
antibodies.append((x, y))
# 开始迭代
for iter in range(max_iter):
# 计算抗体和克隆抗体的适应值
fitnesses = []
for antibody in antibodies:
fitness = f(antibody[0], antibody[1], a, b)
fitnesses.append(fitness)
clone_size = [math.floor(m / (1 + fitness)) for fitness in fitnesses]
# 克隆操作
clones = []
for i in range(n):
for j in range(clone_size[i]):
clones.append(antibodies[i])
# 变异操作
for i in range(len(clones)):
if random.random() < p_mutation:
clones[i] = (clones[i][0] + random.uniform(-1, 1) * l_bound,
clones[i][1] + random.uniform(-1, 1) * l_bound)
# 选择操作
antibodies = []
fitnesses = []
for clone in clones:
if clone[0] > u_bound or clone[0] < l_bound or clone[1] > u_bound or clone[1] <l_bound:
continue
fitness = f(clone[0], clone[1], a, b)
antibodies.append(clone)
fitnesses.append(fitness)
if len(antibodies) < n:
for i in range(n - len(antibodies)):
x = random.uniform(l_bound, u_bound)
y = random.uniform(l_bound, u_bound)
antibodies.append((x, y))
fitnesses.append(f(x, y, a, b))
# 输出当前迭代的最优解
best_fitness = min(fitnesses)
best_antibody = antibodies[fitnesses.index(best_fitness)]
print('Iteration {}: f(x,y) = {}'.format(iter+1, best_fitness))
# 返回最优解
return best_antibody[0], best_antibody[1]
# 运行示例
a = 1
b = 100
n = 50
m = 10
l_bound = -10
u_bound = 10
max_iter = 100
p_mutation = 0.1
x, y = AIS(a, b, n, m, l_bound, u_bound, max_iter, p_mutation)
print('最优解:x = {}, y = {}, f(x,y) = {}'.format(x, y, f(x, y, a, b)))
```
阅读全文