Shortest distance from a point to a plane¶
This example demonstrates how to formulate and solve a least squares method (LSM) optimisation problem using a problem-based approach.
Installing the libraries¶
If your environment does not have the latest version of the JuMP
package installed , uncomment and run the box below:
Pkg.add(["Ipopt", "JuMP"])
#Pkg.add("JuMP");
To launch a new version of the library after the installation is complete, click on the "My Account" button:
Then click on the "Stop" button:
Restart the session by pressing the "Start Engee" button:
Task Description¶
The aim of the problem is to find the shortest distance from the origin (point $(0,0,0)$) to the plane $x_1+2x_2+4x_3=7$.
Thus, the problem is to minimise the function: $$f(x)=x_1^2+x_2^2+x_3^2$$
Given the constraint: $$x_1+2x_2+4x_3=7$$
The function $f(x)$ is the target function and $x_1+2x_2+4x_3=7$ is the equality constraint.
More complex problems may contain other equality constraints, inequality constraints, and upper or lower bound constraints.
Connecting libraries¶
Connect the library JuMP
:
using JuMP;
Connect the nonlinear solver library Ipopt
:
using Ipopt;
Creating an optimisation problem¶
Create an optimisation problem using the function Model()
and specify the name of the solver in brackets:
plane_prob = Model(Ipopt.Optimizer)
Create a variable x
, containing three values, - $x_1$, $x_2$ and $x_3$:
@variable(plane_prob, x[1:3]);
Create a target function to solve the minimisation problem:
@objective(plane_prob, Min, sum(x[i]^2 for i in 1:3))
Set the condition for solving the optimisation problem $x_1+2x_2+4x_3=7$. You can use the function dot()
for the scalar product of two vectors or write the equation in the traditional way:
v = [1, 2, 4]
@constraint(plane_prob, dot(x, v) == 7)
The formulation of the problem is complete. You can review and check the problem:
println(plane_prob)
Problem solution¶
Solve the optimisation problem:
optimize!(plane_prob)
Store the values of x
in a variable:
sol = value.(x);
Output the results of the optimisation. You can use the function round
, to round off excessively accurate values:
println("Оптимизированные значения x = ", round.(sol, digits=4))
Thus, the shortest distance from the point $(0,0,0)$ to the plane $x_1+2x_2+4x_3=7$ is at $(0.3333, 0.6667, 1.3333)$. Now we can calculate the distance between the two points:
origin = [0, 0, 0]
distance = sqrt(sum((sol .- origin).^2))
println("Расстояние ", round(distance, digits=4))
You have found the shortest distance between the origin and the given plane.
Conclusion¶
In this example, we solved the problem of finding the shortest distance from the origin of coordinates (point $(0,0,0)$) to the plane $x_1+2x_2+4x_3=7$ using the least squares method (LSM) using a problem-based approach.