GA算法优化传动比的代码
时间: 2024-06-11 20:02:34 浏览: 19
GA算法可以用来优化传动比,其基本思想是通过种群的选择、交叉和变异等操作,逐步优化传动比的值,直到达到最优解。
下面是一个简单的GA算法优化传动比的代码示例:
```
import random
# 定义适应度函数,计算传动比的值
def fitness(x):
return x ** 2
# 定义GA算法主函数
def ga():
# 初始化种群
population = []
for i in range(10):
population.append(random.uniform(1, 10))
# 迭代次数
num_generations = 50
# 开始迭代
for i in range(num_generations):
# 计算适应度
fitnesses = [fitness(x) for x in population]
# 找出最佳个体
max_fitness = max(fitnesses)
max_index = fitnesses.index(max_fitness)
best_individual = population[max_index]
# 打印最佳个体和适应度
print("Generation {}: Best individual = {:.2f}, Fitness = {:.2f}".format(i, best_individual, max_fitness))
# 选择操作
parents = []
for j in range(5):
parent1_index = random.randint(0, 9)
parent2_index = random.randint(0, 9)
parent1 = population[parent1_index]
parent2 = population[parent2_index]
if fitnesses[parent1_index] > fitnesses[parent2_index]:
parents.append(parent1)
else:
parents.append(parent2)
# 交叉操作
children = []
for j in range(5):
child1 = (parents[j] + parents[j+1]) / 2
child2 = (parents[j] + parents[(j+1)%5]) / 2
children.append(child1)
children.append(child2)
# 变异操作
for j in range(10):
if random.random() < 0.1:
population[j] = random.uniform(1, 10)
# 更新种群
population = parents + children
# 找出最佳个体并返回
fitnesses = [fitness(x) for x in population]
max_fitness = max(fitnesses)
max_index = fitnesses.index(max_fitness)
best_individual = population[max_index]
return best_individual
# 测试代码
best_individual = ga()
print("Best individual found: {:.2f}".format(best_individual))
```