0
$\begingroup$

I want to find the root of a function that has a piecewise part. This means that the value Mathematica will search will determine in which piece of the function we will be. I don't my example is the best, but this is the best example I could think of (and thank you @m_goldberg for helping be to Inactivate the function):

f[a_?NumericQ] := FindRoot[2 x^2 + Log[x] - a, {x, 0.01}][[1, 2]]
f[a_] := Inactivate[FindRoot[2*x^2 + Log[x] - a, {x, 0.01}][[1, 2]], 
  FindRoot | Part]
g[a_] := Piecewise[{{1 - f[a] + Log[f[a]], 
    a <= 1}, {Log[2*f[a]] + f[a], a > 1}}]
Findroot[g[a] + Log[a], {a, 0.1, 0.01, 10}]

Any ideas?

$\endgroup$

1 Answer 1

2
$\begingroup$

I would define g using NumericQ just as you did for f instead of using Inactivate:

f[a_?NumericQ] := FindRoot[2 x^2+Log[x]-a, {x,0.01}][[1,2]]
g[a_?NumericQ] := Piecewise[{
    {1-f[a]+Log[f[a]],a<=1},
    {Log[2*f[a]]+f[a],a>1}
}]

Then try using FindRoot:

FindRoot[g[a] + Log[a], {a,0.1,0.01,10}]

FindRoot::lstol: The line search decreased the step size to within tolerance specified by AccuracyGoal and PrecisionGoal but was unable to find a sufficient decrease in the merit function. You may need more than MachinePrecision digits of working precision to meet these tolerances.

{a -> 1.}

Let's plot your expression over the region of interest:

Plot[g[a] + Log[a], {a, 0, 10}]

enter image description here

The FindRoot message occurs because the root occurs at the piecewise boundary.

$\endgroup$
1
  • $\begingroup$ Thank you very much, @Carl Woll. Indeed my example was not the best because of this boundary issue, but on my problem this is not the case. Thank you again! $\endgroup$
    – Laura K
    Commented Oct 29, 2017 at 18:30

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.