10
$\begingroup$

I'm solving a differential equation numerically by

NDSolve[{p'[r] == -function[r,p[r]], p[0] == pcenter}, p,{r, 0, rmax}] 

with function>0. At some r, p[r] becomes negative. I want NDSolve to stop as soon as this happens and save the value of r. Any ideas how to do this?

$\endgroup$
7
  • 1
    $\begingroup$ WhenEvent is what you want $\endgroup$ Commented Jul 12, 2014 at 12:52
  • $\begingroup$ @acl I posted an answer using what I learned from your comment. Thanks! By the way, I'm involving you in an experiment without your permission (sorry!) $\endgroup$ Commented Jun 5, 2015 at 21:50
  • $\begingroup$ @Ian excellent, up voted. Happy to serve as a guinea pig. $\endgroup$ Commented Jun 5, 2015 at 22:41
  • $\begingroup$ @lan I read through your experiment. I feel reluctant to formally accept your answer though because I never actually tested the code $\endgroup$ Commented Jun 7, 2015 at 16:10
  • $\begingroup$ DanielR I wonder if I could press you to actually test the code and see if it does satisfy your question, in which case it may well deserve acceptance. If at all possible, this would close the circle on @Ian's laudable experiment... Thank you! $\endgroup$ Commented Jun 9, 2015 at 21:21

1 Answer 1

10
$\begingroup$

A WhenEvent[event, action] can be included in the list eqn used in NDSolve[eqn,__]. For example:

eqn = { p'[r] == -p[r] - 1, p[0] == 1, WhenEvent[p[r] == 0, rMax = r; "StopIntegration"] }; sol = NDSolve[eqn, p, {r, 0, \[Infinity]}]; Plot[p[r] /. sol, {r, 0, rMax}] 
$\endgroup$
1
  • 4
    $\begingroup$ FYI: The last r is in fact the endpoint of the domain of the solution. The domain may be obtained with p["Domain"] /. sol. (Of course, it can be convenient to save it in a variable rMax as you did, too.) $\endgroup$ Commented Jun 5, 2015 at 22:18

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.