3
$\begingroup$

My problem is very simple. Assume you have this piece of code :

FindRoot[{x^2 + 1 == 0}, {x, -1, 1}]

Now, this code returns

FindRoot::cvmit: Failed to converge to the requested accuracy or precision within 100 iterations.
{x -> -1.}

Which is as expected since the equation has no real root. Now my question is, how can I get the fact that FindRoot failed in a variable ? Say I want to display a message "Failed search", when FindRoot fails for whatever reason, how do I collect the fact that the function failed ? I was looking into Catch[], but it seems that no exception is thrown.

$\endgroup$
3
  • 6
    $\begingroup$ See Check $\endgroup$
    – Carl Woll
    Commented Dec 10, 2020 at 20:18
  • $\begingroup$ Works great, thanks ! $\endgroup$
    – Frotaur
    Commented Dec 10, 2020 at 20:21
  • $\begingroup$ FindRoot can find complex roots if you tell it to look in the complex plane, e.g., FindRoot[{x^2 + 1 == 0}, {x, -1 + I, 1 + I}] evaluates to {x -> 1.16068*10^-19 + 1. I} $\endgroup$
    – Bob Hanlon
    Commented Dec 11, 2020 at 2:18

1 Answer 1

3
$\begingroup$

To expand @Carl's comment:

res = Check[
  FindRoot[{x^2 + 1 == 0}, {x, -1, 1}], $Failed[Evaluate@$MessageList]]

FindRoot::cvmit: Failed to converge to the requested accuracy or precision within 100 iterations.

(*  $Failed[{FindRoot::cvmit}]  *)

Some ways to query the result res

FreeQ[res, $Failed]   (* True => success *)
(*  False  *)
FreeQ[res, "cvmit"]   (* False => "cvmit" message occurred *)
(*  False  *)
FreeQ[res, FindRoot]  (* False => message(s) from FindRoot occurred *)
(*  False  *)

The structure of res, which is obscured by the standard output form:

FullForm[res]
(*  $Failed[List[HoldForm[MessageName[FindRoot, "cvmit"]]]]  *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.