# Problems with MinimalBy, MaximalBy, SortBy [duplicate]

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)

• In the documentation, look up the first example under "possible issues" on the Sort page Jan 31, 2016 at 9:33

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

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