If I have a function $f(x)$ that I only know numerically and that returns a real value for some range of values $-\infty < x \leq a$ and complex values for $a < x < \infty$, how can I precisely determine what the value of $a$ is?
I know I can generate a table of values of $f(x)$ and see when the transition occurs, but this requires quite a bit of manual work to get to a sufficient degree of precision.
Alternatively, I can try to use FindRoot
in the following way (using $f(x) = \sqrt{2-x}$ as a simple example merely for illustrative purposes):
g[x_] := If[Im[Sqrt[2 - x]] == 0, 0, I]
FindRoot[g[x] == 0, {x, 2.05}]
(Note that I use I
for $x > 2$ because the numerical function that I am trying to work with behaves very strangely for a certain range $a < x < b$ due to some FindRoot
issues, and I don't want any of that strangeness displaying in plots of g[x]
or affecting the calculation of $a$.)
But this returns the following error:
FindRoot::jsing: Encountered a singular Jacobian at the point {x} = {2.05}.
Try perturbing the initial point(s).
I have tried to fix this issue by varying the value of g[x]
for $x > 2$:
g[x_] := If[Im[Sqrt[2 - x]] == 0, 0, 2*x]
In this case, however, FindRoot
does not yield the correct value for $a$, as it uses the slope of $2x$ to return $0$.
In order to use this method, then, I would need to use a function that is equal to $0$ at $a$; without already knowing $a$, however, this does not seem possible.
Is there a better method for solving this problem? Can my approach work with some tweaks? I found this question, but it also seems less precise than I would like, since Plot evaluates only at some points (of course, I could try to restrict the domain to get a better result, but again, that is more manual control than I am aiming for).
Thank you very much!
While[]
orNestWhile[]
might be useful. $\endgroup$