4
n = 1;

MinimalBy[{{0, 0}, {1, -1}}, EuclideanDistance[{1, n}, #] &]
MaximalBy[{{0, 0}, {1, -1}}, EuclideanDistance[{1, n}, #] &]
SortBy[{{0, 0}, {1, -1}}, EuclideanDistance[{1, n}, #] &]

They give:

{{1, -1}}

{{0, 0}}

{{1, -1}, {0, 0}}

But

n = 1.;

MinimalBy[{{0, 0}, {1, -1}}, EuclideanDistance[{1, n}, #] &] MaximalBy[{{0, 0}, {1, -1}}, EuclideanDistance[{1, n}, #] &] SortBy[{{0, 0}, {1, -1}}, EuclideanDistance[{1, n}, #] &]

work fine:

{{0, 0}}

{{1, -1}}

{{0, 0}, {1, -1}}

Version : 10.3.1 for Microsoft Windows (64-bit)

qwerty
  • 1,199
  • 1
  • 7
  • 7

2 Answers2

3

All these functions use Sort to perform their calculations. Sort doesn't work with irrational numbers such as $\sqrt 2$ which you get after taking EuclideanDistance[{1, 1}, {0, 0}]. Simple example like Sort[{2, Sqrt[2]}] also gives you the wrong answer

{2, Sqrt[2]}

The irrational number needs to be changed to a real number by adding the floating point Sort[{2, Sqrt[2.0]}]. Then, as you mentioned, the result is correct

{1.41421, 2}

As nicely added by Szabolcz, you can also use TakeLargestBy where the numerical evaluation N can be applied for sorting (NOTE: TakeLargestBy gives larger values first)

TakeLargestBy[{Sqrt[2], 2}, N, 2]

{2, Sqrt[2]}

Pavlo Fesenko
  • 368
  • 1
  • 10
  • 2
    In recent versions one can also use TakeLargestBy instead of MaximalBy. TakeLargestBy sorts by numerical magnitude. – Szabolcs Jan 31 '16 at 10:01
  • Thank you @Pavlo and @Szabolcs. I understand the behaviour of Sort and try with TakeLargestBy. – qwerty Jan 31 '16 at 10:35
1
EuclideanDistance[{1, n}, #] & /@ {{0, 0}, {1, -1}, {0., 0.}, {1., -1.}}
{Sqrt[2], 2, 1.41421, 2.}
Sort[%]
{1.41421, 2, 2., Sqrt[2]}
FullForm[%]
 List[1.4142135623730951`,2,2.`,Power[2,Rational[1,2]]]

Try

MinimalBy[{{0, 0}, {1, -1}}, N@EuclideanDistance[{1, n}, #] &]
MaximalBy[{{0, 0}, {1, -1}}, N@EuclideanDistance[{1, n}, #] &]
SortBy[{{0, 0}, {1, -1}}, N@EuclideanDistance[{1, n}, #] &]
rhermans
  • 36,518
  • 4
  • 57
  • 149