nlopt quadratic optimization

 

/*
* main.c
*
*  Created on: Oct 9, 2018
*      Author: lgh
*/


#include <stdio.h>
#include <math.h>
#include "nlopt.h"
#define INF 1e10
int i = 0;

double step = 1;

//目标函数;
double utility(unsigned n, const double *x, double *grad, void *data)
{
    if (grad) {
        grad[0] = (-1.0 + x[0])*step;
        grad[1] = (-2.0 + x[2])*step;
    }
    printf("迭代次数 i= %d, x[0]=%f, x[1]= %f,f(x1,x2)=%f\n",
        i++, x[0], x[1], -x[0] - 2 * x[1] + 0.5*x[0] * x[0] + 0.5*x[1] * x[1]);
    return (-x[0] - 2 * x[1] + 0.5 * X [ 0 ] * X [ 0 ] + 0.5 * X [ . 1 ] * X [ . 1 ]); 
} 


// inequality constraints; 
Double inconstraint_1 (n-unsigned, const  Double * X, Double * Grad, void * Data ) 
{ 
    IF (Grad) { 
        Grad [ 0 ] = 2.0 * STEP; 
        Grad [ . 1 ] = 3.0 * STEP; 
    } 
    return ( 2 * X [ 0 ] + . 3 * X [1 ] - . 6 ); 
} 

// inequality constraints; 
Double inconstraint_2 (n-unsigned, const  Double * X, Double * Grad, void * Data) 
{ 
    IF (Grad) { 
        Grad [ 0 ] = 1.0 * STEP; 
        Grad [ 1 ] = 4.0 * STEP; 
    } 
    return (X [ 0 ] + . 4 * X [ . 1 ] - . 5 ); 
} 

// inequality constraints; 
Double inconstraint_3(unsigned n, const double *x, double *grad, void *data)
{
    if (grad) {
        grad[0] = 2.0*step;
        grad[1] = 6.0*x[1] * step;
    }
    return (2 * x[0] + 3 * x[1] * x[1] - 6);
}


int main(int argc, char const *the argv []) 
{ 
    Double Tol = 1E- . 4 ;
     Double LB [ 2 ] = { 0 , 0 };        // X1, x2 of the lower boundary; 
    Double UB [ 2 ] = {INF, INF};
     Double X [ 2 ] = { 1 , 1 };       // to x1, x2 given initial value; 
    Double f_min; 

    nlopt_opt opter = nlopt_create (NLOPT_LD_SLSQP / * NLOPT_LD_MMA * / , 2 ); 

    // set the lower limit of the argument; 
    nlopt_set_lower_bounds (opter, LB);

    // objective function; 
    nlopt_set_min_objective (opter, Utility, NULL); 

    // inequality constraints; 
    nlopt_add_inequality_constraint (opter, inconstraint_1, NULL, Tol); 
    nlopt_add_inequality_constraint (opter, inconstraint_2, NULL, Tol); 
    nlopt_add_inequality_constraint (opter, inconstraint_3, NULL, Tol ); 

    // required conditions stop; 
    nlopt_set_xtol_rel (opter, Tol); 

    // start optimization; 
    nlopt_result nlopt_optimize Result = (opter, X, & f_min); 

    IF (Result) 
    { 
        the printf ( " minimum =% g, = X (% G,% G) \ n- " , f_min, X [ 0 ], X [ . 1 ]); 
    } 

    //free
    nlopt_destroy(opter);
    getchar();
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/luoyinjie/p/11288095.html