I have a function similar to the following example:
f[x_, y_] := (x - 2)^2 + x ( y - 2)^2
and I would like to find the minimum with respect to x and y using FindRoot (the function is not simple enough for analytical minimization and using FindRoot on the derivatives turned out to be orders of magnitude faster than NMinimze). So far, I use
FindRoot[{D[f[x, y], x] == 0 ,
D[f[x, y], y] == 0}, {{x, 1}, {y, 3}}]
(* {x -> 2., y -> 2.} *)
which works most of the time. However, sometimes, my starting guess for x and y is off, like:
FindRoot[{D[f[x, y], x] == 0 ,
D[f[x, y], y] == 0}, {{x, 3}, {y, 20}}]
(* {x -> -4.73317*10^-30, y -> 4.} *)
yielding a wrong solution. I know that I can minimize the function for a given x reliably to obtain y as a function of x:
fy[x_] := FindRoot[{D[f[x, y], y] == 0 }, {{y, 20}}]
The question now is: Can I use this numerical function fy in the FindRoot for x?
I have tried:
FindRoot[{D[f[x, y], x] == 0 /. fy[x]}, {{x, 2}}]
which gives errors like
FindRoot::nlnum: The function value {36. x} is not a list of numbers with dimensions {1} at {y} = {20.}.
Similarly, this also does not work:
FindRoot[{D[f[x, fy[x]], x] == 0 /. fy[x]}, {{x, 2}}]
FindRoot[{D[f[x, fy[x]], x] == 0 /. fy[x]}, {{x, 2}}]
Is there a syntactically proper way to do what I intend to do?
D[f[xs, y], xs] == 0 /. xs -> xandD[f[x, y], x] == 0are exactly the same(D[f[xs, y], xs] == 0 /. xs -> x) === (D[f[x, y], x] == 0)gives True – Stitch Nov 22 '16 at 21:53NArgMinapplied to your function returns the desired result in 23 ms (checkRepeatedTiming[NArgMin[f[x, y], {x, y}]]). Is that really unacceptably slow, given that it will reliably return minima and not generic extrema as your current approach? – MarcoB Nov 23 '16 at 17:58FindRootto minimize wrt. one variable first and then wrt. to the other one, without discussions on how to optimize the minimization of the specific function. In my actual application, the function is more than a page long and involves elliptical functions.FindRootfinds the minimum in a few 100 ms andNMinimizetakes several minutes. Now the difference matters. – Felix Nov 23 '16 at 18:13