# Find Root of a function generated by NDSolve

So I define a function

    fshoot[w_, f0_] := NDSolve[{-w^2 f[x] + Sin[f[x]] - 2 f'[x]/x - f''[x] ==0,
f[xmin] == f0, f'[xmin] == 2 f2[w, f0] xmin + 4 f4[w, f0] xmin^3 + 6 f6[w, f0] xmin^5},
f, {x, xmin, xmax}][[1]]


For each value of f0 and w I get a function f[x] as a solution. Now, I want to fix the value of f0 and find the value w which makes the function f[x] vanish at x=xmax, so I define

    froot[W_] := f[xmax]/.fshoot[W,f0];


Which is a function of W. Now I want to find the root of this function so I run

   FindRoot[froot[W], {W, .98}]


But the problem is that the NDSolve uses W as an unspecified number and so I don't get a numerical value for f[x] which then makes FindRoot unhappy because f[xmax] is not evaluated to a numeric value.

How can I modify my code so that it works?

• what aref2, f4 and f6? Without a minimal example that can be run, we cannot help you. Meanwhile, read WhenEvent information Nov 30 '17 at 13:49
• Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Take the tour and check the faqs! 3) When you see good questions and answers, vote them up by clicking the gray triangles. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! Nov 30 '17 at 17:02

# Quick fix

Quick fix can be achieved just by restricting froot function to take only numerical values:

froot[W_?NumericQ] := f[xmax] /. fshoot[W, f0];


# Proper way

However, your shooting algorithm better use ParametricNDSolveValue function, particularly, its feature to return the value at some point. An example from help (note the second parameter f[10]):

pfun = ParametricNDSolveValue[{f''[t] + a f[t] == 0, f[0] == 1, f'[0] == 0},
f[10], {t, 0, 10}, {a}]

FindRoot[pfun[a], {a, 1}]


Your code:

fshoot[f0_] := ParametricNDSolveValue[{-w^2 f[x] + Sin[f[x]] - 2 f'[x]/x - f''[x] == 0,
f[xmin] == f0,
f'[xmin] == 2 f2[w, f0] xmin + 4 f4[w, f0] xmin^3 + 6 f6[w, f0] xmin^5},
f[xmax], {x, xmin, xmax}, {w}];

froot = fshoot[f0];

FindRoot[froot[W], {W, .98}]