# How can I find the point in a list of points that is nearest to a given point? [duplicate]

I have a function $f(x)=\{\sin(x),\cos(x)\}$, $\,x=\{0,0.01,...,1\},$ and a point $P=\{2,3\}$.

I want to find the $x_0$ such that the distance between $P$ and $f(x_0)$ is minimum.

My code is:

f[x_] := {Sin[x], Cos[x]};
P = {2, 3};
data = f /@ Range[0, 1, 0.01];
Cases[Thread @ {Range[0, 1, 0.01], data}, {_, First @ Nearest[data, P]}][[1,1]]


Is there an easy method to for doing this?

• @corey979 Sorry, I forgot the definition of f, thanks. – user123 Dec 28 '16 at 13:52
• MinimalBy[Range[0,1,0.01],EuclideanDistance[P,f[#]]&]? – N.J.Evans Dec 28 '16 at 16:28
• Possible duplicate: (34746). Also related: (99244) – Michael E2 Jan 2 '17 at 17:51
• Related: (20085) – Mr.Wizard Jan 2 '17 at 22:07

## Using Nearest

I'd proceed along the lines

f[x_] := {x, Sin[x], Cos[x]};
data = f /@ Range[0, 1, 0.01];
P = {2, 3};
near = Nearest[Rest /@ data, P] (* only for comparison with further approaches *)


{{0.556361, 0.830941}}

The position of near in data can be also obtained with Nearest directly:

loc = First @ Nearest[(Rest /@ data) -> Automatic, P]


60

so

x0 = (First /@ data)[[loc]]


0.59

## Exact solution - Region functions

The exact distance from the point P to the curve is

reg = ParametricRegion[Rest @ f[x], {{x, 0, 1}}];
FullSimplify @ RegionDistance[reg, P]


$\sqrt{13}-1\approx 2.60555$

The coordinates (the equivalent of near) on this curve are (i.e., $p=\{\sin x_0, \cos x_0\}$)

RegionNearest[reg, P]
p = FullSimplify @ %


$\left(\frac{2}{\sqrt{13}},\frac{3}{\sqrt{13}}\right)\approx \left( 0.5547, 0.83205\right)$

$x_0$ can be obtained with

sol = Solve[Rest @ f[x] == p, x] // First hence

x0 = x /. sol /. C -> 0


$x_0=\arctan\frac{2}{3}\approx 0.588003$

## Exact solution - calculus

The distance and x0 can be found numerically with

NMinimize[FullSimplify[EuclideanDistance[Rest @ f[x], P], x > 0], x]


{2.60555, {x -> 0.588003}}

The exact value of x0:

g[x_] := FullSimplify[EuclideanDistance[Rest @ f[x], P], x > 0]
Solve[D[g[x], x] == 0, x] so $x_0=\arccos\frac{3}{\sqrt{13}}$.

But because $x\in [0,1]$:

Solve[D[g[x], x] == 0 && 0 < x < 1, x] All forms of the exact values of x0 are equivalent:

ArcTan[2/3] == ArcCos[3/Sqrt] == 2 ArcTan[1/2 (-3 + Sqrt)] // FullSimplify


True

The last one can be also obtained with

ArgMin[EuclideanDistance[Rest @ f[x], P]^2, x]


from Chip Hurst's comment.

• You could use Nearest[(Rest /@ data) -> Automatic, P] to have Nearest return the position rather than the value. – Chip Hurst Dec 28 '16 at 15:27
• Also you could do ArgMin[EuclideanDistance[Rest@f[x], P]^2, x] for an exact solution (+1 by the way). – Chip Hurst Dec 28 '16 at 15:31
• @ChipHurst Thanks; I edited to employ your Nearest. – corey979 Dec 28 '16 at 15:37