4
$\begingroup$
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)

$\endgroup$
  • 1
    $\begingroup$ In the documentation, look up the first example under "possible issues" on the Sort page $\endgroup$ – Coolwater Jan 31 '16 at 9:33
3
$\begingroup$

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]}

$\endgroup$
  • 2
    $\begingroup$ In recent versions one can also use TakeLargestBy instead of MaximalBy. TakeLargestBy sorts by numerical magnitude. $\endgroup$ – Szabolcs Jan 31 '16 at 10:01
  • $\begingroup$ Thank you @Pavlo and @Szabolcs. I understand the behaviour of Sort and try with TakeLargestBy. $\endgroup$ – qwerty Jan 31 '16 at 10:35
1
$\begingroup$
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}, #] &]
$\endgroup$

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