3
$\begingroup$

I want to calculate the diameter of a convex polygon. That is, the largest distance between any pair of vertices. Here's my approach

pol = Polygon@{{-6.4, -8.3}, {-5.5, -9}, {-5, -8.4}, {-5, -7.9}, {-5.9, -7.6}};
vts = pol[[1]];
AbsoluteTiming@
 Max@Table[Table[EuclideanDistance[vts[[i]], vts[[j]]],
  {j, i + 1, Length@vts}], {i, Length@vts - 1}]

(* {0.000058, 1.45602} *)

What do you think? Is there a faster way of doing this?

$\endgroup$

2 Answers 2

5
$\begingroup$
$Version

(* "12.3.1 for Mac OS X x86 (64-bit) (June 19, 2021)" *)

Clear["Global`*"]

pol = Polygon@{{-6.4, -8.3}, {-5.5, -9}, {-5, -8.4}, {-5, -7.9}, \
{-5.9, -7.6}};

vts = pol[[1]];

AbsoluteTiming@Max[EuclideanDistance @@@ Subsets[vts, {2}]]

(* {0.000044, 1.45602} *)
$\endgroup$
2
  • $\begingroup$ Thanks, that's great! It didn't occur to me to use Subsets. I'm running the same version on Windows 10 and I compared both approaches (essentially listed the timings over 10^5 runs and took the mean). Just in case you're curious: my absolute timing converged to $0.000020782$, while yours to $0.0000125165$. $\endgroup$
    – sam wolfe
    Aug 4, 2021 at 13:44
  • 3
    $\begingroup$ See RepeatedTiming $\endgroup$
    – Bob Hanlon
    Aug 4, 2021 at 13:54
5
$\begingroup$

See also DistanceMatrix which is a little slower than Subsets, and Outer which is about the same with this many points:

RepeatedTiming@Max@DistanceMatrix@pol[[1]]

RepeatedTiming[
 Max@Outer[EuclideanDistance, #, #, 1] &@pol[[1]]
 ]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.