5

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?

glS
  • 7,623
  • 1
  • 21
  • 61
user123
  • 385
  • 1
  • 10

1 Answers1

9

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

enter image description here

hence

x0 = x /. sol /. C[1] -> 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]

enter image description here

so $x_0=\arccos\frac{3}{\sqrt{13}}$.

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

Solve[D[g[x], x] == 0 && 0 < x < 1, x]

enter image description here

All forms of the exact values of x0 are equivalent:

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

True

The last one can be also obtained with

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

from Chip Hurst's comment.

corey979
  • 23,947
  • 7
  • 58
  • 101