NLopt
Guidance last updated: 19 October 2026
NLopt is a library for nonlinear local and global optimisation, for functions with and without gradient information. It is designed as a simple, unified interface and packaging of several free and open-source nonlinear optimisation libraries.
Documentation: NLopt source and documentation.
Caution
When compiling R packages that use NLopt, choose R and NLopt modules with compatible compiler toolchains. See R on Stanage.
Usage
After connecting to Stanage (see Establishing a SSH connection), start an interactive session:
salloc
You can load a specific version with the following command:
module load NLopt/2.7.1-GCCcore-13.3.0
Example
The following C example, adapted from the NLopt tutorial, minimises
sqrt(x[1]) subject to two nonlinear constraints. Save it as example.c:
#include <stdio.h>
#include <math.h>
#include <nlopt.h>
// Objective function
double myfunc(unsigned n, const double *x, double *grad, void *my_func_data)
{
if (grad) {
grad[0] = 0.0;
grad[1] = 0.5 / sqrt(x[1]);
}
return sqrt(x[1]);
}
// Constraint data structure
typedef struct {
double a, b;
} my_constraint_data;
// Constraint function
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 main(void)
{
double lb[2] = { -HUGE_VAL, 0 }; /* lower bounds */
nlopt_opt opt;
opt = nlopt_create(NLOPT_LD_MMA, 2); /* algorithm and dimensionality */
if (!opt) return 1;
nlopt_set_lower_bounds(opt, lb);
nlopt_set_min_objective(opt, myfunc, NULL);
// Adding inequality constraints
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); // Stopping criteria
double x[2] = { 1.234, 5.678 }; /* initial guess */
double minf; /* minimum objective value */
// Perform optimisation
if (nlopt_optimize(opt, x, &minf) < 0) {
fprintf(stderr, "nlopt failed!\n");
nlopt_destroy(opt);
return 1;
}
else {
printf("found minimum at f(%g,%g) = %0.10g\n", x[0], x[1], minf);
}
nlopt_destroy(opt); // Clean up
return 0;
}
Compile and run the example with:
gcc example.c -o example -lnlopt -lm
./example
The minimum should be close to 0.544331, at approximately
x[0] = 0.333333 and x[1] = 0.296296.
Installation notes
NLopt was installed using Easybuild, build details can be found in $EBROOTNLOPT/easybuild with a given module loaded.