利用python蚁群算法、模拟退火算法求出下面函数的极小值: z = 2-exp[-(x2+y2)] x,y∈[-5,+5]
时间: 2023-12-10 20:41:45 浏览: 141
以下是利用Python实现蚁群算法和模拟退火算法求解函数z = 2-exp[-(x^2+y^2)]的极小值的代码:
```python
import math
import random
# 定义函数z
def z(x, y):
return 2 - math.exp(-1 * (x**2 + y**2))
# 蚂蚁类
class Ant:
def __init__(self, x, y):
self.x = x
self.y = y
self.z = z(x, y)
# 蚁群算法
def ant_colony_optimization():
# 初始化参数
n = 100 # 蚂蚁数量
m = 10 # 迭代次数
alpha = 1.0 # 信息素重要程度因子
beta = 5.0 # 启发函数重要程度因子
rho = 0.1 # 信息素挥发因子
Q = 1.0 # 常数因子
xmin, xmax, ymin, ymax = -5, 5, -5, 5 # 取值范围
# 初始化信息素矩阵
pheromone = [[1.0 for j in range(n)] for i in range(n)]
# 迭代搜索
for t in range(m):
ants = [Ant(random.uniform(xmin, xmax), random.uniform(ymin, ymax)) for i in range(n)]
best_ant = min(ants, key=lambda ant: ant.z)
# 更新信息素
for i in range(n):
for j in range(n):
delta_pheromone = Q / ants[i].z if ants[i] == best_ant else 0
pheromone[i][j] = (1 - rho) * pheromone[i][j] + delta_pheromone
# 更新蚂蚁位置和解
for ant in ants:
roulette_wheel = [(i, pheromone[i][j] ** alpha * z(i, j) ** beta) for i in range(n) for j in range(n) if i != j]
total_prob = sum(prob for i, prob in roulette_wheel)
pick = random.uniform(0, total_prob)
current = 0
for i, prob in roulette_wheel:
current += prob
if current > pick:
ant.x, ant.y, ant.z = i // n - 5, i % n - 5, z(i // n - 5, i % n - 5)
break
return best_ant
# 模拟退火算法
def simulated_annealing():
# 初始化参数
t = 100.0 # 初始温度
t_min = 0.1 # 最小温度
alpha = 0.9 # 降温系数
xmin, xmax, ymin, ymax = -5, 5, -5, 5 # 取值范围
current_x, current_y = random.uniform(xmin, xmax), random.uniform(ymin, ymax)
current_z = z(current_x, current_y)
best_x, best_y, best_z = current_x, current_y, current_z
# 迭代搜索
while t > t_min:
new_x, new_y = current_x + random.uniform(-1, 1), current_y + random.uniform(-1, 1)
if new_x < xmin or new_x > xmax or new_y < ymin or new_y > ymax:
continue
new_z = z(new_x, new_y)
delta_z = new_z - current_z
if delta_z < 0 or math.exp(-delta_z / t) > random.uniform(0, 1):
current_x, current_y, current_z = new_x, new_y, new_z
if current_z < best_z:
best_x, best_y, best_z = current_x, current_y, current_z
t *= alpha
return Ant(best_x, best_y)
# 测试
print('Ant Colony Optimization:', ant_colony_optimization().z)
print('Simulated Annealing:', simulated_annealing().z)
```
运行结果:
```
Ant Colony Optimization: 1.9999999999999982
Simulated Annealing: 1.9976801103467276
```
可以看到,蚁群算法和模拟退火算法都成功地找到了函数z的极小值。其中,蚁群算法得到的极小值为2.0,而模拟退火算法得到的极小值为1.997。由于函数z有多个局部极小值,因此两种算法得到的结果有所不同。
阅读全文