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

黄金分割搜索法求单峰极小值C++实现

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

黄金分割搜索法求单峰极小值C++实现

#ifndef GOLDEN_SEARCH_H
#define GOLDEN_SEARCH_H


double golden_min(double a, double b, double eps, double f ( double x ), double &x);

#endif // GOLDEN_SEARCH_H
#include "golden_search.h"
#include "math.h"
#include "assert.h"
#include 

double golden_min(double a, double b, double eps, double f(double), double &x)
{
    //a----c--d----b
    //ac为小头,bc为大头, ac=db, bc/ab为黄金分割比例
    double result = NAN;
    const double GR = (sqrt(5.0) - 1.0)/2.0; //黄金分割比例, golden ratio
    double c = a + (b-a) * (1 - GR);
    double fc = f(c);

    bool bTure = (fc <= f(a) && fc <= f(b));
    if (!bTure)
    {
        //初始参数不满足f(c) <= f(a)和f(b)
        assert(false);
        return result;
    }

    //保护措施,防止函数不满足条件等导致的死循环
    const int max_times = 3000;
    int times = 0;

    bool bSwapCD = false;
    double d, fd;
    while (true)
    {
        //安全保护
        times++;
        if (times > max_times)
        {
            result = fc;
            break;
        }

        c = a + (b-a) * (1 - GR);
        d = a + (b-a) * GR;

        if (bSwapCD)
        {
            fc = f(c);
        }
        else
        {
            fd = f(d);
        }

        if (c > d)
        {
            assert(false);
        }

        if (fabs(a - b) < eps * qMin(fabs(a), fabs(b)))
        {
            x = (a + b) / 2;
            result = f(x);
            //std::cout <<  "times:" << times;
            break;
        }

        if (fc <= fd)
        {
            b = d;
            fd = fc;
            bSwapCD = true;
        }
        else
        {
            a = c;
            fc = fd;
            bSwapCD = false;
        }
    }

    return result;
}
#include 
#include 
#include "golden_search.h"

static int T = 0;
typedef double (*func) (double);

static double myfunc2(double x)
{
    T++;
    return pow(x, 2)  -200 * x + 10000.0;
}

static void test_min(double a, double b, double eps, func f)
{
    QElapsedTimer timer;
    timer.start();

    double x3 = 0, fx3 = 0;

    int times = 1000;
    T = 0;
    timer.restart();
    for (int i = 0; i < times; i++)
    {
        fx3 = golden_min(a, b, eps, f, x3);
    }
    qDebug () << "golden_min       "
              << "x="  << QString::number(x3, 'E', 14)
              << "fx=" << QString::number(fx3 , 'E', 14)
              << timer.nsecsElapsed() / 1000000.0
              << "ms, times:" << T/times;
}


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    test_min(-1e100, 1e100, 1.0e-14, myfunc2);

    return a.exec();
}

运行输出:

golden_min x= "9.99999999789266E+1" fx= "0.00000000000000E+0" 22.8964 ms, times: 543

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/690374.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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