3
$\begingroup$

I want to define a function as the result of FindRoot. This function will be used in other functions. For example:

f[a_] := FindRoot[2*x^2 + Log[x] - a, {x, 0.01}][[1, 2]];
g[a_] := 1 - f[a]; 

When I plug in numbers for a, there everything works perfectly:

f[1]
g[1]
0.787179
0.212821

The problem happens when I am defining other functions that will use f[a] and g[a] in symbolic terms:

h[a_]:=5*f[a];
h[a]
5 Log[x]

This happens because when I call f[a] in a symbolic way the result is the following, which is wrong:

f[a]
Log[x]

I am clearly not defining f[a] properly or calling it properly in symbolic terms. Any ideas? Thank you!

$\endgroup$
2
  • $\begingroup$ If you run FindRoot[2*x^2 + Log[x] - a, {x, 0.01}][[1, 2]] without a numeric value of a, then you get an error. $\endgroup$
    – bill s
    Oct 28, 2017 at 22:22
  • $\begingroup$ Yes, of course. Maybe I was not very clear. I want to put a "hold" on the FindRoot so I can use f[a] and g[a] symbolically until they are finally evaluated. $\endgroup$
    – Laura K
    Oct 28, 2017 at 23:20

1 Answer 1

3
$\begingroup$

Maybe something like this?

Clear[f]
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]

f[1]

0.787179

f[a]
Inactive[Part][Inactive[FindRoot][-a + 2*x^2 + Log[x], {x, 0.01}], 1, 2]
h[a_] := 5 f[a]
ih = h[a]
5 Inactive[Part][Inactive[FindRoot][-a + 2 x^2 + Log[x], {x, 0.01}], 1, 2]
hv = ih /. a -> 1 // Activate

3.93589

hv/f[1]

5.

$\endgroup$
1
  • $\begingroup$ That is absolutely great. Thank you very much, @m_goldberg! $\endgroup$
    – Laura K
    Oct 29, 2017 at 15:06

Your Answer

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

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