Problems with MinimalBy, MaximalBy, SortBy

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

Posted 2016-01-31T08:20:31.863

Reputation: 1 179

Question was closed 2016-01-31T10:34:06.140

1In the documentation, look up the first example under "possible issues" on the Sort page – Coolwater – 2016-01-31T09:33:55.953

Answers

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

Posted 2016-01-31T08:20:31.863

Reputation: 358

2In recent versions one can also use TakeLargestBy instead of MaximalBy. TakeLargestBy sorts by numerical magnitude. – Szabolcs – 2016-01-31T10:01:26.370

Thank you @Pavlo and @Szabolcs. I understand the behaviour of Sort and try with TakeLargestBy. – qwerty – 2016-01-31T10:35:12.583

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

Posted 2016-01-31T08:20:31.863

Reputation: 26 859