# Small quadratic programming problem - a simple Fortran code needed

I need to find a distance from a point in 3D space to a parallelepiped (a crystal lattice cell). The problem boils down to a quadratic programming task:

Let $$L$$ be a matrix of lattice vectors (row-wise); $$q$$ is a point to find a distance from. Then the problem is following:

$$\min_{\textbf{x}} |L^T \textbf{x} - \textbf{q} |^2 \\ \forall i=1..3 : 0 \leq \textbf{x}_i \leq 1$$

or equivalently

$$\min_{\textbf{x}} \frac{1}{2} \textbf{x}^TLL^T\textbf{x} - \textbf{x}^T L \textbf{q}\\ \forall i=1..3 : 0 \leq \textbf{x}_i \leq 1$$

This is obviously a QP problem with inequality constraints. And there are many methods and libraries capable of solving it. However, I don't want to bring an additional library into the project for a minor task. Given that it is a small problem, with fixed dimensions and simple constraints, I have a hope, that it is possible to get a simple self-contained Fortran code that would solve it. Perhaps there is a solver with a code generator for small cases.

• As a rule of thumb, whenever you find yourself using the word "obviously", it's a good time to take a step back and question yourself. Calculating the distance from a point to a quadrilateral in 3d space can be done with an explicit formula; this doesn't require general methods to solve an optimisation problem. A parallelepiped is just the union of six quadrilaterals.
– Stef
Commented Dec 24, 2023 at 12:28
• Related question: Distance between a point and rectangle in 3D space (although the question is about rectangles, the answer applies equally well to non-rectangular parallelograms).
– Stef
Commented Dec 24, 2023 at 15:08
• @Stef, sure. But it turned out, that the BVLS solution takes less code, than the geometrical one from Burkardt. Commented Dec 24, 2023 at 16:15