Point to line distance in GeometryBasics or another geometry package

I’m seeing a lot of interesting examples here, I want to join the fun too! Here’s an example using CGAL.jl, akin to @Orbots’ Grassmann.jl example:

julia> using CGAL, BenchmarkTools

julia> a, n = Point3(1, 2, 3), Vector3(1, 1, 1)
(PointC3(1, 2, 3), VectorC3(1, 1, 1))

julia> p = Point3(4, 6, 6)
PointC3(4, 6, 6)

julia> l = Line3(a, n)
Line_3(PointC3(1, 2, 3), PointC3(2, 3, 4))

julia> @btime √squared_distance($p, $l)
  13.499 ns (0 allocations: 0 bytes)
0.816496580927726

As mentioned, CGAL doesn’t directly provide absolute distance computation. One could however just create a wrapping function around squared_distance:

julia> distance(a, b) = √squared_distance(a, b)
distance (generic function with 1 method)

julia> @btime distance($p, $l)
  13.526 ns (0 allocations: 0 bytes)
0.816496580927726

Here’s a benchmark that includes Line3 creation too:

julia> @btime distance($p, Line3($a, $n))
  108.824 ns (1 allocation: 16 bytes)
0.816496580927726
3 Likes

Hi there all,

Just a word to say that Eberly has finally release his new “Geometric Tools” v5 those days @ https://github.com/davideberly/GeometricTools .

5 Likes

If the point and line are represented by vectors p and l respectively

using LinearAlgebra
norm(cross(l, p))/norm(l)

In this formula, the vector l is parallel to the line and p = p1 - p0, where the point p0 is on the line and p1 is a point outside the line. Basically, we move the line to the origin. It measures how far p1 is from the line.

Example
using StaticArrays, LinearAlgebra
p0, v = SA[1.0, 2, 3], SA[1.0, 1, 1]        # line: point + vector
p1 = SA[4., 6., 6.]                         # external point
norm(cross(v, p1 - p0))/norm(v)             # Distance: 0.8165; 4.1 ns (0 allocs: 0 bytes)