import numpy as np
# 定义适应度函数
def fitness_func(x):
return sum(x**2)
# 初始化金豺群体
def init_jackal_population(num_jackals, dim):
jackals = []
for i in range(num_jackals):
jackal = np.random.uniform(low=-5, high=5, size=dim)
jackals.append(jackal)
return jackals
# 计算每个金豺的适应度值
def calc_fitness(jackals):
fitness = []
for jackal in jackals:
fitness.append(fitness_func(jackal))
return fitness
# 选择领袖金豺
def select_leader_jackal(jackals, fitness):
idx = np.argmin(fitness)
return jackals[idx]
# 更新金豺位置
def update_jackal_position(jackal, leader_jackal, a, r1, r2):
new_jackal = jackal + a * (np.exp(-r1) - np.exp(-r2)) * np.abs(leader_jackal - jackal)
return new_jackal
# 运行金豺优化算法
def run_gjo(num_iterations, num_jackals, dim):
# 初始化金豺群体
jackals = init_jackal_population(num_jackals, dim)
# 计算每个金豺的适应度值
fitness = calc_fitness(jackals)
# 选择领袖金豺
l