nlopt在windows上的安装使用

nlopt在windows上的安装使用

目录


一、nlopt下载

1.下载nlopt库:https://nlopt.readthedocs.io/en/latest/

2.解压

3.下载dll和def:http://ab-initio.mit.edu/wiki/index.php?title=NLopt_on_Windows\&redirect=no

二、def转lib

1.利用mingw中的dlltool工具,将def换位lib:dlltool -d libnlopt-0.def -l libnlopt-0.lib -k

2.把nlopt.h、nlopt.c和libnlopt-0.lib拉到文件夹下

3.在tasks.json的args里加上"D:\test\libnlopt-0.lib"

三、代码

c 复制代码
#include <stdio.h>
#include <math.h>
#include "nlopt.h"
#define INF (1.0/0.0)

double utility(unsigned n, const double *x, double *grad, void *data){
  grad[0]=1.0/x[0];
  grad[1]=1.0/x[1];
  printf("%f, %f, %f ", x[0],x[1],log(x[0])+log(x[1]));
  return log(x[0])+log(x[1]);
}

double constraint(unsigned n, const double *x, double *grad, void *data){
  double *p=(double *)data;
  grad[0]=*p;
  grad[1]=*(p+1);
  printf("Constraint: %f\n", x[0]*(*p)+x[1]*(*(p+1))-5);
  return x[0]*(*p)+x[1]*(*(p+1))-5;
}

double inconstraint(unsigned n, const double *x, double *grad, void *data){
  grad[0]=1;
  grad[1]=-1;
  return x[0]-x[1];
}

int main(int argc, char const *argv[]) {
  double p[2]={1,2};
  double tol=1e-8;
  double lb[2]={-INF,-INF};
  double ub[2]={INF,INF};
  double x[2]={1,1};
  double f_max=-INF;
  // set up optimizer
  nlopt_opt opter=nlopt_create(NLOPT_LD_SLSQP, 2);
  // lower and upper bound
  nlopt_set_lower_bounds(opter, lb);
  nlopt_set_upper_bounds(opter, ub);
  // objective function
  nlopt_set_max_objective(opter, utility, NULL);
  // equality constraint
  nlopt_add_equality_constraint(opter, constraint, p, tol);
  // inequality constraint
  nlopt_add_inequality_constraint(opter, inconstraint, NULL, tol);
  // stopping criterion
  nlopt_set_xtol_rel(opter, tol);
  nlopt_set_ftol_abs(opter, tol);
  nlopt_set_force_stop(opter, tol);
  // optimize
  nlopt_result result=nlopt_optimize(opter, x, &f_max);
  if (result)
    printf("Maximum utility=%f, x=(%f,%f)\n", f_max, x[0], x[1]);
  // free
  nlopt_destroy(opter);
  return 0;
}
相关推荐
歪歪1004 小时前
qt creator新手入门以及结合sql server数据库开发
c语言·开发语言·后端·qt·数据库开发
凤年徐7 小时前
C++类和对象(上):从设计图到摩天大楼的构建艺术
c语言·开发语言·c++·类和对象
CYRUS_STUDIO11 小时前
LLVM 不止能编译!自定义 Pass + 定制 clang 实现函数名加密
c语言·c++·llvm
CYRUS_STUDIO11 小时前
OLLVM 移植 LLVM 18 实战,轻松实现 C&C++ 代码混淆
c语言·c++·llvm
南山十一少11 小时前
STM32CubeMX + HAL 库:基于 I²C 通信的 BMP280气压海拔测量
c语言·stm32·嵌入式硬件
lingran__13 小时前
C语言制作扫雷游戏(拓展版赋源码)
c语言·算法·游戏
77qqqiqi14 小时前
学习结构体
c语言·学习
学习噢学个屁14 小时前
基于STM32智能阳台监控系统
c语言·stm32·单片机·嵌入式硬件
房开民1 天前
使用海康机器人相机SDK实现基本参数配置(C语言示例)
c语言·数码相机·机器人
Tina表姐1 天前
(C题|NIPT 的时点选择与胎儿的异常判定)2025年高教杯全国大学生数学建模国赛解题思路|完整代码论文集合
c语言·开发语言·数学建模