nloptd 0.3.0 released
jmh530
john.michael.hall at gmail.com
Fri Nov 27 14:24:18 UTC 2026
I’ve released nloptd 0.3.0, the first update to the package in
about ten years. It now relies on importC instead of hand-written
bindings. GPT-6.2 Astra did all the work on this version.
NLopt is a library for nonlinear optimization. With nloptd, you
can write an objective function in D, choose a solver, and supply
bounds or nonlinear constraints.
Here’s a small example: find the point closest to 2, subject to
`x ≤ 1`. The objective captures `target` and writes the
derivative when the solver requests it.
```d
import nloptd;
import std.stdio : writeln;
void main()
{
double target = 2;
auto opt = Optimizer(Algorithm.ldSLSQP, 1);
opt.setMinObjective((x, gradient) {
const delta = x[0] - target;
if (gradient.length) gradient[0] = 2 * delta;
return delta * delta;
});
opt.setUpperBounds(1.0);
opt.setXTolRel(1e-9);
opt.setMaxEvaluations(200);
double[1] point = [0.25];
auto result = opt.optimizeInPlace(point[]);
writeln(point[], " ", result);
}
```
The solver finishes at `x = 1`, where the objective value is also
1. The callback receives D slices over NLopt’s coordinate and
gradient buffers, so neither array needs to be copied.
To try it, install the native NLopt library and headers, then run
`dub add nloptd at 0.3.0` in your DUB project. The wrapper uses
ImportC to read the installed `nlopt.h`. If you need the C API
directly, import `nloptd.raw`. I tested the example above with
the published package on Windows x64 and Ubuntu x86-64 using LDC
1.43.0.
[Package on DUB](https://code.dlang.org/packages/nloptd) · [Setup
instructions and
examples](https://github.com/jmh530/nloptd#readme)
The API has changed since 0.2.1. The [migration
guide](https://github.com/jmh530/nloptd/blob/master/MIGRATION.md)
walks through the same optimization problem with both versions.
More information about the Digitalmars-d-announce
mailing list