Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
WhenEvent is what you want – acl Jul 12 '14 at 12:52
exactly. thank you! – tonydo Jul 12 '14 at 12:54
@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!) – Ian Jun 5 '15 at 21:50
@Ian excellent, up voted. Happy to serve as a guinea pig. – acl Jun 5 '15 at 22:41
@lan I read through your experiment. I feel reluctant to formally accept your answer though because I never actually tested the code – tonydo Jun 7 '15 at 16:10
up vote 4 down vote accepted

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}]
share|improve this answer
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.) – Michael E2 Jun 5 '15 at 22:18

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.