Find the root of a numerical function that contains a root-finding itself?

I have encountered the following problem:

  • define a numerical function h with input x and output y
  • use FindRoot to find the root x* of h
  • one characteristic of h: at some part within h FindRoot is called

I have done that with other software, but its not working in Mathematica, or I am doing something wrong. I have attached a MWE.

Simply evaluating the function h works, but FindRoot does return many error messages. I really do not understand why.

Any ideas?

Best,
Benjamin

h[inp_] :=
 Module[{y, x, a, equ, sol, z},
  
  a = inp;
  
  equ = {x + .5 y - a[[1]], x + y - a[[2]]};
  sol = FindRoot[equ, {{x, 1.0}, {y, 1.0}}];
  
  z = {x, y} /. sol;
  
  z - {1, 1}
  ]
XY = {X, Y};
XYval = {1.5, 2.0};
XYStart = {{XY[[1]], XYval[[1]]}, {XY[[2]], XYval[[2]]}};

h[XYval]

FindRoot[h[XYInput], XYStart]

MHandDWI_BX_p_outerloop_MWE.nb (19.1 KB)

XYInput is nowhere defined… (use XY instead).

You might also want to change the “signature” of h slightly, e.g. to h[inp : {_?NumberQ, _?NumberQ}]:=.... This will enforce that it never be invoked with symbolic parameters.

Great, that actually works. What exactly was the problem? I guess that Mathematica first tried to evaluate h symbolically, which now is not happening.

Thanks a lot.

MHandDWI_BX_p_outerloop_MWE.nb (19.5 KB)