本站所有资源均为高质量资源,各种姿势下载。
下面是用遗传算法求解最小值的代码。遗传算法是一种启发式搜索算法,它模拟了生物进化的过程,逐步搜索解决方案,以找到最优解。这种算法适用于解决复杂的优化问题,例如最小化函数。
代码如下:
```
# 遗传算法求最小值
import random
# 目标函数
def fitness(x):
return x ** 2
# 生成染色体
def gene():
return random.uniform(-10, 10)
# 交叉
def crossover(parent1, parent2):
child1 = (parent1 + parent2) / 2
child2 = (parent1 - parent2) / 2
return child1, child2
# 变异
def mutation(child):
return child + random.uniform(-1, 1)
# 生成初始种群
population = [gene() for i in range(10)]
# 迭代
for i in range(100):
# 计算适应度
fitnesses = [fitness(x) for x in population]
# 选择
parents = random.choices(population, weights=fitnesses, k=2)
# 交叉
children = crossover(*parents)
# 变异
children = [mutation(child) for child in children]
# 替换
population[random.randint(0, 9)] = children[0]
population[random.randint(0, 9)] = children[1]
# 输出最优解
print(min(population, key=fitness))
```
这段代码可以用来解决各种最小化问题,只需要修改 `fitness(x)` 函数即可。