0
$\begingroup$

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?

$\endgroup$

2 Answers 2

3
$\begingroup$

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]}]}]

solution

$\endgroup$
9
  • $\begingroup$ 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. $\endgroup$
    – No name
    Commented May 17, 2020 at 2:23
  • 1
    $\begingroup$ "I was looking for the numerical value" - if you evaluated the code above, did you try evaluating just xv in a separate cell? $\endgroup$ Commented May 17, 2020 at 2:24
  • $\begingroup$ Oh, the graph don't appear in mathematica V.12, I don't know what I'm doing wrong. $\endgroup$
    – No name
    Commented May 17, 2020 at 2:25
  • 1
    $\begingroup$ 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. $\endgroup$ Commented May 17, 2020 at 2:27
  • 1
    $\begingroup$ @Cruz - try the plot now $\endgroup$
    – Bob Hanlon
    Commented May 17, 2020 at 2:54
3
$\begingroup$

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} *)
$\endgroup$

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.