首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >[C++]nlopt在vs2019配置后测试代码

[C++]nlopt在vs2019配置后测试代码

作者头像
云未归来
发布2025-07-22 13:21:08
发布2025-07-22 13:21:08
8700
代码可运行
举报
运行总次数:0
代码可运行

代码:

代码语言:javascript
代码运行次数:0
运行
复制
#include<nlopt.h>
#include<nlopt.hpp>
typedef struct
{
       double a, b;
}my_constraint_data;
double myconstraint(unsigned n, const double *x, double *grad, void *data)
{
       my_constraint_data *d = (my_constraint_data *)data;
       double a = d->a, b = d->b;
       if (grad)
       {
              grad[0] = 3 * a*(a*x[0] + b)*(a*x[0] + b);
              grad[1] = -1.0;
       }
       return ((a*x[0] + b)*(a*x[0] + b)*(a*x[0] + b) - x[1]);
}
int count = 0;
double myfunc(unsigned n, const double *x, double *grad, void *my_func_data)
{
       ++count;
       if (grad)
       {
              grad[0] = 0.0;
              grad[1] = 0.5 / sqrt(x[1]);
       }
       return sqrt(x[1]);
}
int main()
{
       double lb[2] = { -HUGE_VAL, 0 };
       nlopt_opt opt;
       opt = nlopt_create(NLOPT_LD_MMA, 2);
       nlopt_set_lower_bounds(opt, lb);
       nlopt_set_min_objective(opt, myfunc, NULL);
       my_constraint_data data[2] = { { 2, 0 }, { -1, 1 } };
       nlopt_add_inequality_constraint(opt, myconstraint, &data[0], 1e-8);
       nlopt_add_inequality_constraint(opt, myconstraint, &data[1], 1e-8);
       nlopt_set_xtol_rel(opt, 1e-4);
       double x[2] = { 1.234, 5.678 };
       double minf;
       if (nlopt_optimize(opt, x, &minf) < 0)
       {
              printf("nlopt faild!\n");
       }
       else
       {
              printf("found minimum after %d evaluations\n",count);
              printf("found minimum at f(%g,%g)=&0.10g\n", x[0], x[1], minf);
       }
       nlopt_destroy(opt);
       system("pause");
       return 0;
}

运行结果:

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-11-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档