import numpy as np import random # 定义目标函数 def func(x): # 将二进制编码解码为实数 x_decoded = int(x, 2) / (2 ** 20 - 1) * 9 + 1 # 映射到1-10的范围 return x_decoded + 10 * np.sin(5 * x_decoded) + 7 * np.cos(4 * x_decoded) # 初始化种群 def initialize_population(pop_size, gene_length): population = [] for _ in range(pop_size): individual = ''.join(random.choice('01') for _ in range(gene_length)) population.append(individual) return population # 选择操作(轮盘赌选择) def selection(population, fitnesses): max_fit = sum(fitnesses) pick = random.uniform(0, max_fit) current = 0 for ind, fit in zip(population, fitnesses): current += fit if current > pick: return ind # 交叉操作(单点交叉) def crossover(parent1, parent2): point = random.randint(1, len(parent1) - 1) child1 = parent1[:point] + parent2[point:] child2 = parent2[:point] + parent1[point:] return child1, child2 # 变异操作(随机位翻转) def mutate(individual, mutation_rate): if random.random() < mutation_rate: point = random.randint(0, len(individual) - 1) individual = individual[:point] + ('1' if individual[point] == '0' else '0') + individual[point + 1:] return individual # 计算适应度 def evaluate_population(population): fitnesses = [func(ind) for ind in population] return fitnesses # 遗传算法主循环 def genetic_algorithm(pop_size, gene_length, max_generations, crossover_rate, mutation_rate): population = initialize_population(pop_size, gene_length) for generation in range(max_generations): fitnesses = evaluate_population(population) # 选择下一代 new_population = [] for _ in range(pop_size // 2): parent1 = selection(population, fitnesses) parent2 = selection(population, fitnesses) # 交叉 child1, child2 = crossover(parent1, parent2) # 变异 child1 = mutate(child1, mutation_rate) child2 = mutate(child2, mutation_rate) new_population.extend([child1, child2]) population = new_population # 打印当前代的最优解 fitnesses = evaluate_population(population) best_ind = population[np.argmax(fitnesses)] best_value = fitnesses[np.argmax(fitnesses)] print(f"Generation {generation+1}: Best value = {best_value}, x (binary) = {best_ind}, x (decoded) = {int(best_ind, 2) / (2 ** 20 - 1) * 9 + 1}") # 输出最终结果 fitnesses = evaluate_population(population) best_ind = population[np.argmax(fitnesses)] best_value = fitnesses[np.argmax(fitnesses)] print(f"Final Best value = {best_value}, x (binary) = {best_ind}, x (decoded) = {int(best_ind, 2) / (2 ** 20 - 1) * 9 + 1}") # 参数设置 pop_size = 50 gene_length = 20 max_generations = 100 crossover_rate = 0.8 # 注意:虽然设置了,但在上面的交叉函数中未直接使用(可以改为概率性调用) mutation_rate = 0.1 # 运行遗传算法 genetic_algorithm(pop_size, gene_length, max_generations, crossover_rate, mutation_rate)