The Nearest
function accepts a customized distance function. For example, a simple case that works well is
myDist[x_, y_] := Abs[x - y];
data = RandomVariate[UniformDistribution[{0, 1000}], 100];
nf = Nearest[data, DistanceFunction -> myDist]
So for instance, the 5 (random) numbers in data
that are nearest 100 are
nf[100, 5]
For this particular function, I could have used DistanceFunction->EuclideanDistance
. But I ultimately need more flexibility, to have a distance function that depends on another parameter. A simple example would be something like
myDist2[x_, y_, t_] := If[Abs[x - y] > t, t, Abs[x - y]];
where the distance is sort of as before, but if it is above the value of t
, it returns t
(the actual function is considerably more complicated, but this one already reveals the problem). The goal is to use myDist2
in some way -- here are some of the statements that don't work
nf = Nearest[data, DistanceFunction -> myDist2[0.5]]
nf = Nearest[data, DistanceFunction -> myDist2[x, y, 0.5]]
nf = Nearest[data, DistanceFunction -> myDist2[#1, #2, 0.5] &]
nf = Nearest[data, DistanceFunction -> myDist2[#1, #2, 0.5]] &
nf = Nearest[data, DistanceFunction -> myDist2[#[[1]], #[[2]], 0.5] &]
(I know some of these don't make any syntactic sense, but they show how I was flailing around.) These give a variety of errors, most of which are that the
The user-supplied distance function myDist2 does not give a real numeric distance
Presumably, these are not calling myDist2
properly. One fix would be to make the third parameter global, but this is probably a bad idea since it is embedded in a pretty complicated setting. So the question is how to add an extra parameter to the user-specified distance function.