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?
MaximalByreturns a list of results; that pattern is not found in your input, soPositioncorrectly returns an empty list. The following will work:Position[example, First@ MaximalBy[...]]if you just want the first occurrence, orPosition[example, Alternatives@@ MaximalBy[...]]if you want them all. – MarcoB Mar 14 '22 at 11:30SetPrecision,RandomRealcan take the optionWorkingPrecision, e.g.,example = RandomReal[{0, 1}, {10, 10}, WorkingPrecision -> 200]– Bob Hanlon Mar 14 '22 at 14:08