使用遗传算法来计算函数 f(x) = x + 10*sin(5*x) + 7*cos(4*x) 的最优值

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值