遗传模拟退火算法代码
时间: 2024-03-31 09:31:05 浏览: 15
遗传模拟退火算法是一种优化算法,用于在搜索空间中找到最优解。下面是一个简单的遗传模拟退火算法的代码示例:
```python
import random
import math
# 定义问题的目标函数
def objective_function(x):
return x**2
# 定义遗传模拟退火算法
def genetic_simulated_annealing():
# 初始化参数
population_size = 100 # 种群大小
chromosome_length = 10 # 染色体长度
mutation_rate = 0.01 # 变异率
temperature = 100 # 初始温度
cooling_rate = 0.95 # 冷却率
# 初始化种群
population = []
for _ in range(population_size):
chromosome = [random.randint(0, 1) for _ in range(chromosome_length)]
population.append(chromosome)
# 迭代搜索
while temperature > 0.01:
for i in range(population_size):
# 计算个体适应度
x = int(''.join(map(str, population[i])), 2)
fitness = objective_function(x)
# 生成新个体
new_chromosome = population[i].copy()
for j in range(chromosome_length):
if random.random() < mutation_rate:
new_chromosome[j] = 1 - new_chromosome[j]
# 计算新个体适应度
new_x = int(''.join(map(str, new_chromosome)), 2)
new_fitness = objective_function(new_x)
# 判断是否接受新个体
if new_fitness < fitness or random.random() < math.exp((fitness - new_fitness) / temperature):
population[i] = new_chromosome
# 降低温度
temperature *= cooling_rate
# 返回最优解
best_chromosome = population[0]
for chromosome in population:
x = int(''.join(map(str, chromosome)), 2)
if objective_function(x) < objective_function(int(''.join(map(str, best_chromosome)), 2)):
best_chromosome = chromosome
return int(''.join(map(str, best_chromosome)), 2)
# 调用遗传模拟退火算法
best_solution = genetic_simulated_annealing()
print("最优解:", best_solution)
```