# FindRoot over a domain, but give domain boundary if no root exists

I call

r = x /. FindRoot[f[x] == 0, {x, 0, -5, 5}]


f[x] is always monotonic, but sometimes it doesn't have a root in the specified interval (–5, 5), so I might, for instance, get the error

FindRoot::reged: "The point {5} is at the edge of the search region...


Rather than raising an error, I would like simply to assign the value 5 to r in this case. Likewise, if FindRoot hits the left edge of the region without finding a root, I would like to assign the value -5 to r.

Using Check[…] would allow me to determine if the reged error has occurred, but that is not enough information to solve this problem; in order to set r to the correct value, I need the additional fact of whether FindRoot ran into the left edge of the region or the right edge.

• having an example f[x] will help. – Nasser Nov 10 '14 at 7:43
• Since $f$ is monotonic, you can just pick the endpoint which has the smaller absolute value of $f$. As a bonus, you can do this without needing to call FindRoot because that's just going to produce an error anyway. – Rahul Nov 10 '14 at 7:55
• Sorry, "because" should have been "when": If both endpoints have the same sign, that's when you can pick the appropriate endpoint without calling FindRoot. – Rahul Nov 10 '14 at 8:29
• Actually FindRoot returns the edge-value in case of an error by default (at least in Mathematica 10) – funnyp0ny Nov 10 '14 at 8:36
• Is there a Closed: OP is incredibly stupid category? If not, I guess you can feel free to post "It already does that by itself, doofus" as an answer and I'll accept it? – thecommexokid Nov 10 '14 at 9:07

As requested by the OP: "It already does that by itself, doofus" :)

• MinimalBy is new to Mma 10, in which @funnypony claims the functionality I desire is the default behavior of FindRoot anyhow, and so requires no special solution. I myself am still using Mma 9. – thecommexokid Nov 10 '14 at 8:55
• Actually, I've come to realize that @funnypony was right, and FindRoot does do what I want automatically, rendering the whole question moot. This answer should still be correct, just totally unnecessary. – thecommexokid Nov 10 '14 at 9:02
• That's what I get for answering on my phone, I suppose. Fixed now :) – Rahul Nov 10 '14 at 9:45