栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

模拟退火算法

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

模拟退火算法

前几天计算智能方法的实验作业,简单封装了一下,可以直接调用。

等有空了再完善。

class SimulateAnneal {
  private:
    double eps;
    double inf;
    int itercnt;

  public:
    SimulateAnneal() {
        eps = 1e-12;
        inf = 2e12;
        itercnt = 0;
    }
    double getEps() const { return eps; }
    double getInf() const { return inf; }
    int getItercnt() const { return itercnt; }
    void setEps(const double &_eps) { eps = _eps; }
    void setInf(const double &_inf) { inf = _inf; }

    std::function defaultExponentCooling =
        [](double temp) -> double { return temp * 0.998; };
    std::function defaultLinearCooling =
        [](double temp) -> double { return temp - 0.168; };

    std::function defaultInverseCooling =
        [](double temp) -> double { return temp / (0.0012 * temp + 1); };
    std::function defaultQuickCooling =
        [&](double temp) -> double { return temp / (getItercnt() + 1); };
    std::function defaultLogarithmicCooling =
        [&](double temp) -> double { return 3000.0 / (std::log1p(getItercnt()) + 1); };

    template 
    std::pair>
    solve(std::vector &initial,
          const std::function &)> &calc,
          const std::function &better,
          const std::function(std::vector &, double)> &change,
          const std::function &CoolingSchedule,
          double temperature) {
        std::vector current = initial;
        std::vector ret = initial;
        T ans = calc(current);
        itercnt = 0;
        std::uniform_real_distribution P(0, 1.0);
        std::random_device rd;
        std::default_random_engine engine{rd()};
        while (temperature > eps) {
            std::vector now = change(current, temperature);
            T value = calc(now);
            double delta = -fabs(value - ans);
            if (better(value, ans)) {
                current = now;
                ret = now;
                ans = value;
            } else if (exp(delta / temperature) > P(engine)) {
                current = now;
            }
            temperature = CoolingSchedule(temperature);
            itercnt++;
        }
        return {ans, ret};
    }
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/938326.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号