Skip to main content

equation solving - How to correct this, `f[a_] := FindRoot[eq == 0, {x, 0.5}]`, where `eq` contains a parameter $a$, without using `eq[a]`?


I want to solve an equation with a parameter $a$, and define the result as a function of $a$. It is something like this:


f[a_] := FindRoot[x^2 + 2 x + a == 0, {x, 0.5}]

f[0.2]
(* -> {x -> -0.105573} *)

The equation I want to solve is a large expression, so I do not want to put it explicitly inside the FindRoot. But this does not work:


eq := x^2 + 2 x + a;
f[a_] := FindRoot[eq == 0, {x, 0.5}]
f[0.2]
(* -> FindRoot::nlnum: The function value {1.25 +a} is not a list of numbers with dimensions {1} at {x} = {0.5}. *)

I do not want to define the equation as eq[a], because this equation is also used to do other things, for which it is better to just use eq. The following ways also do not work:



f[a_] := FindRoot[Evaluate[eq] == 0, {x, 0.5}]
f[a_] := Evaluate[FindRoot[eq == 0, {x, 0.5}]]

(However, if we want to solve the above equation analytically, f[a_] := Evaluate[Solve[eq == 0, x]] works, and f[a_] := Solve[Evaluate[eq] == 0, x] does not. How to explain this?)



Answer



To achieve what you want, you can use the following


eq := x^2 + 2 x + a;
Function[f[a_] := FindRoot[# == 0, {x, 0.5}]][eq]

to define your f.



Comments