天气与日历 切换到窄版

 找回密码
 立即注册
中国膜结构网
十大进口膜材评选 十大国产膜材评选 十大膜结构设计评选 十大膜结构公司评选
查看: 91|回复: 1

c++代码 遗传算法 包含轮盘赌

[复制链接]
  • TA的每日心情
    开心
    2024-8-31 15:58
  • 签到天数: 89 天

    [LV.6]常住居民II

    488

    主题

    207

    回帖

    3366

    积分

    管理员

    积分
    3366
    发表于 2024-6-22 09:46:18 | 显示全部楼层 |阅读模式
    1. #include <iostream>
    2. #include <vector>
    3. #include <random>
    4. #include <cmath>
    5. // 适应度函数(示例)
    6. double fitness(int value) {
    7.     return std::abs(value - 50); // 假设我们想要接近值50
    8. }
    9. // 轮盘赌选择
    10. int rouletteWheelSelection(const std::vector<double>& probabilities) {
    11.     std::random_device rd;
    12.     std::mt19937 gen(rd());
    13.     std::uniform_real_distribution<> dis(0.0, probabilities.back());
    14.     double sum = std::accumulate(probabilities.begin(), probabilities.end(), 0.0);
    15.     double randomValue = dis(gen);
    16.     double cumulative = 0.0;
    17.     for (size_t i = 0; i < probabilities.size(); ++i) {
    18.         cumulative += probabilities[i] / sum;
    19.         if (randomValue < cumulative)
    20.             return i;
    21.     }
    22.     return probabilities.size() - 1; // 如果随机值大于所有概率之和,返回最后一个索引
    23. }
    24. int main() {
    25.     // 参数设置
    26.     const int populationSize = 100;
    27.     const int generations = 200;
    28.     const double mutationRate = 0.01;
    29.     // 初始化种群
    30.     std::vector<int> population(populationSize);
    31.     for (int& individual : population) {
    32.         individual = std::rand() % 100; // 初始化为0到99之间的随机数
    33.     }
    34.     // 主循环:遗传算法
    35.     for (int generation = 0; generation < generations; ++generation) {
    36.         std::vector<double> fitnessValues(populationSize);
    37.         std::vector<double> accumulatedFitness(populationSize);
    38.         // 计算适应度和累积适应度
    39.         for (size_t i = 0; i < population.size(); ++i) {
    40.             fitnessValues[i] = fitness(population[i]);
    41.             accumulatedFitness[i] = accumulatedFitness[i - 1] + fitnessValues[i];
    42.         }
    43.         accumulatedFitness[populationSize - 1] = accumulatedFitness[populationSize - 2] + fitnessValues[populationSize - 1];
    44.         // 选择、交叉和变异操作
    45.         std::vector<int> newPopulation(populationSize);
    46.         for (size_t i = 0; i < population.size(); ++i) {
    47.             // 轮盘赌选择
    48.             int parent1 = rouletteWheelSelection(accumulatedFitness);
    49.             int parent2 = rouletteWheelSelection(accumulatedFitness);
    50.             // 交叉(这里使用简单的一点交叉)
    51.             int crossoverPoint = std::rand() % 100; // 随机选择交叉点
    52.             newPopulation[i] = (parent1 * (100 - crossoverPoint) + parent2 * crossoverPoint) / 100;
    53.             // 变异
    54.             if (std::rand() < mutationRate * RAND_MAX) {
    55.                 newPopulation[i] = std::rand() % 100; // 变异为新随机数
    56.             }
    57.         }
    58.         // 更新种群
    59.         population = newPopulation;
    60.         // 输出当前代的最优解
    61.         double bestFitness = *std::min_element(population.begin(), population.end(), [](int a, int b) { return fitness(a) > fitness(b); });
    62.         std::cout << "Generation " << generation << ": Best Fitness = " << bestFitness << std::endl;
    63.     }
    64.     return 0;
    65. }
    复制代码

     

     

     

     

    c++代码   遗传算法 包含轮盘赌
    中国膜结构网打造全中国最好的膜结构综合平台 ,统一协调膜结构设计,膜结构施工,膜材采购,膜材定制,膜结构预算全方位服务。 中国空间膜结构协会合作单位。
  • TA的每日心情
    开心
    昨天 15:13
  • 签到天数: 153 天

    [LV.7]常住居民III

    3456

    主题

    553

    回帖

    214748万

    积分

    管理员

    中国膜结构网www.mjgou.com

    积分
    2147483647
    QQ
    发表于 2024-6-29 16:48:49 | 显示全部楼层
    遗传算法是一种搜索启发式算法,灵感来源于自然选择和遗传学原理,常用于优化和搜索问题。下面是一个简化的遗传算法示例,使用轮盘赌选择(roulette wheel selection)来进行个体的选择,以解决一个简单的最大化问题。我们将尝试最大化一个由二进制编码表示的目标函数。
    1. ```cpp
    2. #include <iostream>
    3. #include <vector>
    4. #include <cstdlib>
    5. #include <ctime>
    6. #include <algorithm>
    7. #include <numeric>
    8. // 个体类
    9. class Individual {
    10. public:
    11.     std::vector<int> genes; // 基因,即二进制编码
    12.     double fitness; // 适应度
    13.     Individual(int geneLength) : genes(geneLength), fitness(0.0) {
    14.         // 初始化基因
    15.         for (int& g : genes) {
    16.             g = rand() % 2;
    17.         }
    18.     }
    19.     void calculateFitness() {
    20.         // 假设目标函数是要最大化二进制编码表示的十进制数
    21.         fitness = std::accumulate(genes.begin(), genes.end(), 0.0,
    22.                                   [](double total, int bit) { return total * 2 + bit; });
    23.     }
    24. };
    25. // 轮盘赌选择
    26. Individual rouletteWheelSelection(const std::vector<Individual>& population) {
    27.     double totalFitness = std::accumulate(population.begin(), population.end(), 0.0,
    28.                                           [](double total, const Individual& ind) { return total + ind.fitness; });
    29.     double pick = static_cast<double>(rand()) / RAND_MAX * totalFitness;
    30.     double current = 0.0;
    31.     for (const auto& individual : population) {
    32.         current += individual.fitness;
    33.         if (current > pick) {
    34.             return individual;
    35.         }
    36.     }
    37.     // 默认返回最后一个个体
    38.     return population.back();
    39. }
    40. // 遗传算法主循环
    41. void geneticAlgorithm(int populationSize, int geneLength, int generations) {
    42.     srand(static_cast<unsigned int>(time(nullptr)));
    43.     std::vector<Individual> population(populationSize);
    44.     for (auto& individual : population) {
    45.         individual.genes.resize(geneLength);
    46.     }
    47.     for (int generation = 0; generation < generations; ++generation) {
    48.         for (auto& individual : population) {
    49.             individual.calculateFitness();
    50.         }
    51.         // 打印当前最优个体的适应度
    52.         std::sort(population.begin(), population.end(),
    53.                   [](const Individual& a, const Individual& b) { return a.fitness > b.fitness; });
    54.         std::cout << "Generation " << generation << ": Best Fitness = " << population.front().fitness << std::endl;
    55.         std::vector<Individual> newPopulation;
    56.         while (newPopulation.size() < populationSize) {
    57.             Individual parent1 = rouletteWheelSelection(population);
    58.             Individual parent2 = rouletteWheelSelection(population);
    59.             // 进行交叉和变异,生成新个体
    60.             Individual child = parent1; // 假设无交叉,直接复制父代
    61.             // 变异操作
    62.             for (int i = 0; i < geneLength; ++i) {
    63.                 if (static_cast<double>(rand()) / RAND_MAX < 0.05) { // 变异概率5%
    64.                     child.genes[i] = 1 - child.genes[i];
    65.                 }
    66.             }
    67.             newPopulation.push_back(child);
    68.         }
    69.         population = newPopulation;
    70.     }
    71. }
    72. int main() {
    73.     geneticAlgorithm(100, 10, 100); // 100个个体,每个个体10个基因,运行100代
    74.     return 0;
    75. }
    76. ```
    复制代码

    在上述代码中,我们定义了一个`Individual`类来表示个体,它包含了一组基因(`genes`)和一个适应度值(`fitness`)。遗传算法的主要循环包括计算适应度、轮盘赌选择、交叉和变异等步骤。这里为了简化,我们省略了交叉操作,只进行了变异。轮盘赌选择是基于个体适应度的大小来进行选择,适应度越高的个体被选中的概率越大。

    请注意,遗传算法的效果很大程度上取决于问题的特性、种群大小、基因长度、交叉和变异策略等参数的设置。在实际应用中,可能需要对这些参数进行调整以获得最佳效果。

     

     

     

     

    c++代码   遗传算法 包含轮盘赌
    中国膜结构网打造全中国最好的膜结构综合平台 ,统一协调膜结构设计,膜结构施工,膜材采购,膜材定制,膜结构预算全方位服务。 中国空间膜结构协会合作单位。
    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|Archiver|手机版|中国膜结构网|中国膜结构协会|进口膜材|国产膜材|ETFE|PVDF|PTFE|设计|施工|安装|车棚|看台|污水池| |网站地图

    GMT+8, 2024-9-8 09:23 , Processed in 0.066063 second(s), 26 queries .

    Powered by Discuz! X3.5

    © 2001-2024 Discuz! Team.

    快速回复 返回顶部 返回列表