參考博客:
https://blog.csdn.net/dshl9595/article/details/77169162
https://blog.csdn.net/u014571489/article/details/79344676
1、官網下載 優化庫,參考現有博客,建議下載 nlopt-2.4.2-dll32.zip
https://github.com/stevengj/nlopt/releases/tag/nlopt-2.4.2
2、
3、編譯:
先輸入nlopt優化庫所在盤: E:
再輸入:cd E:\nlopt 回車 ,進入了該文件夾。
輸入:lib /def:libnlopt-0.def 回車,即可在nlopt文件夾下發現
4、最後將新生成的.dll文件複製到VS2010的安裝目錄下,VC\bin 中
5、新建工程,項目屬性配置
6、測試程序
#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)=%g\n", x[0], x[1], minf);
}
nlopt_destroy(opt);
system("pause");
return 0;
}