# Assigning a given value if a function returns an error [duplicate]

This question has to do with error handling, I guess.

I am using Brent's Method in order to numerically find the root of a function. This is just an example of what I am doing:

functionexample[a_, b_, c_, x_] := Sin[a*x] + Cos[b*x] + Log[c*x]
rootexample[a_, b_, c_, result_] :=
FindRoot[functionexample[a, b, c, x] == result, {x, 1, 12},
Method -> "Brent", PrecisionGoal -> 16][[1]][[2]]
a = 1
b = 1
c = 1
Plot[{functionexample[a, b, c, x], 2, 4}, {x, 1, 12},
PlotRange -> Automatic]
rootexample[a, b, c, 2]
rootexample[a, b, c, 4]


And this is what I get:

So, at the end rootexample[1, 1, 1, 4] (that's when Brent's Method returns an error message) seems to take value 4.

I would like to define rootexample[a_, b_, c_, result_] in such a way that when an error arises in the root finding procedure, an special value is assigned to the result of the function (something like "" or Null or None or something similar).

[EDIT: The idea is: if there is a root, then return the root; if not, then return None.]

I mean, I would like to properly control/handle possible errors coming from Brent's Method within the definition of the function rootexample.

I have no idea about how to do this.

Like stated in the duplicate's link:

functionexample[a_, b_, c_, x_] := Sin[a*x] + Cos[b*x] + Log[c*x]
rootexample[a_, b_, c_, result_] :=
FindRoot[functionexample[a, b, c, x] == result, {x, 1, 12},
Method -> "Brent", PrecisionGoal -> 16][[1, 2]]
a = 1; b = 1; c = 1;
Quiet[Table[
Check[rootexample[a, b, c, i], "NaN", {FindRoot::bbrac}], {i, -5, 5}],
{FindRoot::bbrac}]


{NaN,NaN,NaN,NaN,NaN,NaN,NaN,5.68433,NaN,NaN,NaN}

Or if you want it as a function:

quietrootexample[a_, b_, c_, result_] :=
Quiet@Check[rootexample[a, b, c, result], "NaN", {FindRoot::bbrac}]
quietrootexample[a, b, c, #] & /@ Range@5


{NaN,5.68433,NaN,NaN,NaN}

• Thank you. I don't know what to do about the "duplicating" issue. I think the other question is very similar, but I wanted it to be applied to a function. In fact, even if I had seen that possible duplicate, I would still have asked my question. And, actually... I still have to check and understand what is the meaning of that syntax, with @ and so on —I am still a beginner on Mathematica. Jul 10 '14 at 14:47
• @Vicent Quiet[...] is equivalent to Quiet@...
– Öskå
Jul 10 '14 at 14:50
• Thank you! I find the syntax of Mathematica a little bit strange sometimes, but it is very powerful, I think. Jul 10 '14 at 15:08