# FindMinimum can't evaluate Nearest numerically

I'm trying to use Nearest as a function to minimize over: a toy example is

f[z_] := FindMinimum[First@Nearest[Range@9 -> "Distance", x], {x,z}]


An expected result is f[5.6]=6. I'm aware there are simpler ways to write such a function; the goal is to minimze with Nearest.

I tried with Unevaluated and Inactive in various spots, but no matter what I get the error

The default distance function does not give a real numeric distance when applied to the point pair x and 1.

Then FindMinimum complains about a nonnumeric function value. It's worth noting that any symbolic call to Nearest gives the same error; the problem is that FindMinimum can't inject the parameter.

## Question

How can I properly delay the evaluation of Nearest such that it may be evaluated by FindMinimum?

f[x_] := First@Nearest[Range@9 -> "Distance", x]
FindMinimum[Hold@f@X, {X, 5.6}]


This doesn't seem to generalize when I do multidimensional minimizations.

• No, x should be arbitrary. For some reason extracting to a delayed function makes it work albeit with errors
Commented Sep 22, 2023 at 5:20
• Perhaps f[x_?NumericQ] := First@Nearest[Range@9 -> "Distance", x]? Commented Sep 22, 2023 at 14:52

\$Version

(* "13.3.1 for Mac OS X ARM (64-bit) (July 24, 2023)" *)

Clear["Global*"]


Nearest is already doing a minimization, FindMinimum is not needed.

First@Nearest[Range[9], 5.6]

(* 6 *)


To do a minimization with distance,

ArgMin[{EuclideanDistance[{x}, {5.6}], 1 <= x <= 9}, x, Integers]

(* 6 *)
`