# What's the difference between TakeLargestBy and MaximalBy? [closed]

I find most examples in doc of MaximalBy can be replaced by TakeLargestBy, and the result is the same.

MaximalBy[{e1,e2,e3},f] == TakeLargestBy[{e1,e2,e3},f,1]

MaximalBy[{e1,e2,e3},f,n] == TakeLargestBy[{e1,e2,e3},f,n]

MaximalBy[f] == TakeLargestBy[f,1]


Just in this case they have difference,TakeLargestBy will drop Null,None,Indeterminate,Missing. And the order of element returned by these two functions is not the same.

So what the purpose of design these two functions,it looks do the same thing.

• Because they don't "do the same thing". Have you read the documentation at all? Try, e.g., TakeLargestBy[s, #^2 &, 5] and MaximalBy[s, #^2 &, 5] with s={-7, -10, 7, -8, 6} – ciao Dec 15 '17 at 5:21
• TakeLargestBy sorts the e_i by numerical magnitude. MaximalBy return the maximal e_i are returned in the order they appear in the input. – partida Dec 15 '17 at 5:26

I know of two differences between MaximalBy and TakeLargestBy -- there may more I am not aware of.

1. MaximalBy[data, f, n] is equivalent to Take[SortBy[data, OrderedQ /* f], -n] while TakeLargestBy[data, f, n] is equivalent to Take[SortBy[data, N /* f], -n]

2. The argument n is optional in MaximalBy[data, f, n] and defaults to 1 while it is required in TakeLargestBy[data, f, n]

The first difference will not matter if all the elements in list satisfy NumberQ, but may give unexpected results from MaximalBy when one or more elements only satisfy the weaker predicate NumericQ. For example (taken from section Possible Issues of in the article ref/MaximalBy,

data = {BesselJ[0, 1], BesselJ[1, 1]};
N @ data


{0.765198, 0.440051}

MaximalBy[data, Identity, 1]


{BesselJ[1, 1]} (* which is smaller thanBesselJ[0, 1] *)

However, TakeLargestBy gets it right.

TakeLargestBy[data, Identity, 1]


{BesselJ[0, 1]}`