# How to use NDSolve and NSolve together

I have a differential equation that I can't solve analytically, so I use NDSolve to get a solution.

Suppose that I can't solve the next equation

sol = NDSolve[{D[p[x]/(1 + x)^3, x] == 0, p[0] == 1}, p, {x, 0, 1000}]


And know that I have the numerical solution, I want to find a solution of the equation $$p[x]=100$$ using NSolve:

NSolve[(p[x] /. sol) == 100, x, Reals]


However, it doesn't work.

If I have the analytical solution of the differential equation this is easy, I just have to do the next,

Solve[(1 + x)^3 == 100, x, Reals]


Any recommendations?

The usual way to go about this is to use the event detection capabilities of NDSolve[], through WhenEvent[]:

{sol, {{xv}}} =
Reap[NDSolveValue[{D[p[x]/(1 + x)^3, x] == 0, p[0] == 1,
WhenEvent[p[x] == 100, Sow[x], "LocationMethod" -> "Brent"]},
p, {x, 0, 1000}]];

Plot[sol[x], {x, 0, 10}, GridLines -> {None, {100}},
Epilog -> {Directive[ColorData[97, 2], AbsolutePointSize[6]], Point[{xv, sol[xv]}]}]


• I was looking for the numerical value, since I need this value for multiple calculations, it will be slow if I extract every single time the value from the graph. Commented May 17, 2020 at 2:23
• "I was looking for the numerical value" - if you evaluated the code above, did you try evaluating just xv in a separate cell? Commented May 17, 2020 at 2:24
• Oh, the graph don't appear in mathematica V.12, I don't know what I'm doing wrong. Commented May 17, 2020 at 2:25
• Just to be sure, please evaluate this on a freshly launched Mathematica instance. If that doesn't work, please take a screenshot and put it in a comment. Commented May 17, 2020 at 2:27
• @Cruz - try the plot now Commented May 17, 2020 at 2:54

Just drop the domain restriction. The domain restriction requires that all variables and functions to include intermediate values be real. Presumably, at some point Mathematica can't determine that and gives up.

Clear["Global*"]

\$Version

(* "12.1.0 for Mac OS X x86 (64-bit) (March 14, 2020)" *)

sol = NDSolve[{D[p[x]/(1 + x)^3, x] == 0, p[0] == 1}, p, {x, 0, 1000}][[1]];

NSolve[(p[x] /. sol) == 100, x][[1]] // Quiet

(* {x -> 3.64159} *)

Solve[(p[x] /. sol) == 100, x][[1]] // Quiet

(* {x -> 3.64159} *)
`