使用了遗传算法对函数 f(x)=xsin(10πx)+1.0 进行优化,求出其最大值,其中 x 属于[-1,2]。
时间: 2023-12-31 22:05:06 浏览: 102
遗传算法_遗传算法求函数最大值_
5星 · 资源好评率100%
好的,我来回答你的问题。以下是代码实现:
```python
import random
import math
# 定义适应度函数
def fitness(x):
return x * math.sin(10 * math.pi * x) + 1.0
# 定义选择算法
def selection(population):
fitness_list = [fitness(x) for x in population]
total_fitness = sum(fitness_list)
probability_list = [fitness / total_fitness for fitness in fitness_list]
cum_probability_list = []
cum_probability = 0.0
for probability in probability_list:
cum_probability += probability
cum_probability_list.append(cum_probability)
selected_population = []
for i in range(len(population)):
r = random.random()
for j in range(len(cum_probability_list)):
if r < cum_probability_list[j]:
selected_population.append(population[j])
break
return selected_population
# 定义交叉算法
def crossover(population, crossover_rate):
offspring_population = []
for i in range(len(population) // 2):
parent1 = population[i * 2]
parent2 = population[i * 2 + 1]
if random.random() < crossover_rate:
crossover_point = random.randint(1, len(parent1) - 2)
offspring1 = parent1[:crossover_point] + parent2[crossover_point:]
offspring2 = parent2[:crossover_point] + parent1[crossover_point:]
else:
offspring1 = parent1
offspring2 = parent2
offspring_population.append(offspring1)
offspring_population.append(offspring2)
return offspring_population
# 定义变异算法
def mutation(population, mutation_rate):
mutated_population = []
for individual in population:
mutated_individual = []
for gene in individual:
if random.random() < mutation_rate:
mutated_gene = gene + random.uniform(-0.1, 0.1)
if mutated_gene < -1:
mutated_gene = -1
elif mutated_gene > 2:
mutated_gene = 2
mutated_individual.append(mutated_gene)
else:
mutated_individual.append(gene)
mutated_population.append(mutated_individual)
return mutated_population
# 初始化种群
def initialize_population(population_size):
population = []
for i in range(population_size):
individual = [random.uniform(-1, 2) for j in range(10)]
population.append(individual)
return population
# 主函数
def main():
population_size = 50
generations = 100
crossover_rate = 0.8
mutation_rate = 0.2
population = initialize_population(population_size)
for i in range(generations):
population = selection(population)
population = crossover(population, crossover_rate)
population = mutation(population, mutation_rate)
best_individual = max(population, key=fitness)
print("最大值为:", round(fitness(best_individual), 6))
print("最优解为:", best_individual)
if __name__ == '__main__':
main()
```
注:本代码使用了遗传算法对函数 f(x)=x*sin(10π*x)+1.0 进行优化,求出其最大值。其中,种群规模为50,迭代次数为100次,交叉概率为0.8,变异概率为0.2。在运行代码时,会输出最大值和最优解。
阅读全文