1
$\begingroup$

In for example this answer a solution is given to find the position of a maximal value. However, this solutions seems to run into trouble when dealing with precision numbers. Take the following example:

example = SetPrecision[RandomReal[{0, 1}, {10, 10}]
   , 200];
Position[example, MaximalBy[example, #[[2]] &]]

The expectation is that this will produce some position. Instead it givesd {} because no match is found. One can check by hand if the "maximal" entry is say the first one (once can repalce the first 10 in the above code with 1 so that this is always true) that

MatchQ[example[[1]],MaximalBy[example, #[[2]] &]]

indeed returns false despite these entries looking the same and originating from the same source. The issue seems to be in the precision numbers involved.

How do I get a robust version of a functionpositionMaximalBy that returns the position of the element that MaximalBy outputs?

$\endgroup$
3
  • 4
    $\begingroup$ I don't think the precision of the arguments has anything to do with this. Instead, MaximalBy returns a list of results; that pattern is not found in your input, so Position correctly returns an empty list. The following will work: Position[example, First@ MaximalBy[...]] if you just want the first occurrence, or Position[example, Alternatives@@ MaximalBy[...]] if you want them all. $\endgroup$
    – MarcoB
    Commented Mar 14, 2022 at 11:30
  • $\begingroup$ Oops that was stupid. $\endgroup$
    – Kvothe
    Commented Mar 14, 2022 at 13:45
  • $\begingroup$ As an alternative to using SetPrecision, RandomReal can take the option WorkingPrecision, e.g., example = RandomReal[{0, 1}, {10, 10}, WorkingPrecision -> 200] $\endgroup$
    – Bob Hanlon
    Commented Mar 14, 2022 at 14:08

0