使用遗传算法 - 函数最优解计算相关代码,求解f(x)在区间 [0,5] 上的最大值:f(x)=xsin(10x)+xcos(2x)
时间: 2024-12-17 10:42:14 浏览: 8
yichuansuanfa.rar_求函数最大值_遗传算法
遗传算法是一种基于自然选择原理的优化搜索算法,通常用于解决复杂函数的全局优化问题。在Python中,可以使用`deap`库来实现遗传算法寻找函数`f(x)`= `x * sin(10*x) + x * cos(2*x)`在区间[0, 5]上的最大值。以下是一个简化的示例:
```python
import numpy as np
from deap import base, creator, tools
# 定义函数 f(x)
def fitness_function(solution):
x = solution[0]
return -solution[0] * np.sin(10 * x) - solution[0] * np.cos(2 * x)
# 初始化遗传算法参数
creator.create("FitnessMax", base.Fitness, weights=(-1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
toolbox = base.Toolbox()
toolbox.register("attr_float", lambda: np.random.uniform(0, 5))
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, n=1)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
toolbox.register("evaluate", fitness_function)
toolbox.register("mate", tools.cxTwoPoint)
toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=0.1, indpb=0.1)
toolbox.register("select", tools.selTournament, tournsize=3)
# 设置其他算法参数,如种群大小、代数等
POPULATION_SIZE = 100
MAX_GENERATIONS = 1000
pop = toolbox.population(n=POPULATION_SIZE)
hof = tools.HallOfFame(1) # 保存最佳个体
for gen in range(MAX_GENERATIONS):
offspring = toolbox.select(pop, len(pop))
offspring = [toolbox.clone(ind) for ind in offspring]
# 遗传操作
for child1, child2 in zip(offspring[::2], offspring[1::2]):
if np.random.rand() < 0.7:
toolbox.mate(child1, child2)
del child1.fitness.values
del child2.fitness.values
for mutant in offspring:
if np.random.rand() < 0.1:
toolbox.mutate(mutant)
del mutant.fitness.values
invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
fitnesses = map(toolbox.evaluate, invalid_ind)
for ind, fit in zip(invalid_ind, fitnesses):
ind.fitness.values = fit
pop[:] = offspring
best_solution = hof.items[0] if hof else None
print(f"经过{gen+1}代迭代,找到的最大值约为 {best_solution[0]:.4f}")
阅读全文