非线性优化库 NLopt 使用

1. 安装

下载 v2.6.2.tar.gz

mkdir build
cd build
cmake ..
sudo make install

2. CMakeLists 配置

cmake_minimum_required(VERSION 3.1)
project(Nlopt-Test)

set (CMAKE_CXX_STANDARD 11)

find_package(NLopt REQUIRED)

include_directories(
    ${
    
    NLopt_INCLUDE_DIRS}
)
 
#nlopt_test
add_executable(nlopt_test src/nlopt_test.cpp)
target_link_libraries(nlopt_test ${
    
    NLOPT_LIBRARIES})

2. 使用

例子:
在这里插入图片描述

#include <iostream>
#include <stdio.h>
#include <math.h>
#include "nlopt.h"
#define INF (1.0/0.0)
int i = 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]));
    printf("迭代次数 i= %d, x[0]=%f, x[1]= %f,f(x1,x2)=%f\n",i++,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]={
    
    0,0};
    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;
}

结果:

迭代次数 i= 0, x[0]=1.000000, x[1]= 1.000000f(x1,x2)=0.000000
Constraint: -2.000000
迭代次数 i= 1, x[0]=1.666667, x[1]= 1.666667f(x1,x2)=1.021651
Constraint: 0.000000
Maximum utility=1.021651, x=(1.666667,1.666667)

猜你喜欢

转载自blog.csdn.net/qq_35632833/article/details/118446666