[?] Set an endpoint to NDSolve?

I’m trying to tell NDSolve to stop at a specific point when a variable reaches a certain value. Here is a minimal example

ode1 = {x'[t] == -1, x[0] == 1, y'[t] + y[t] x[t]^2 == 100, y[0] == 10}; sol = NDSolve[ode1, {x, y}, {t, 0, tf}];

I need tf to be the point when x reaches zero.

Hi,

Does WhenEvent work for you?

ode1 = {x'[t] == -1, x[0] == 1, y'[t] + y[t] x[t]^2 == 100,  y[0] == 10, WhenEvent[x[t] == 0, "StopIntegration"]}; 
sol1 = NDSolve[ode1, {x, y}, {t, 0, 3}];

If you look at the resulting InterpolatingFunction, it lives on the domain from 0 to 1.

Cheers,

Marco

Thanks for your answer. But how do I know the value of t for x[t] == 0? Also I tried a plot and it looks like x[t] continues beyond x=0 which is not what I’d excpect

ode1 = {x'[t] == -1, x[0] == 1, y'[t] + y[t] x[t]^2 == 100, 
   y[0] == 10, WhenEvent[x[t] == 0, "StopIntegration"]};
sol1 = NDSolve[ode1, {x, y}, {t, 0, 10}]; Plot[{x[t] /. sol1}, {t, 0, 
  10}]

Well, you said

“stop at a specific point when a variable reaches a certain value”

so you probably need to know the value? Or a condition that needs to be fulfilled to stop the integration?

And yes, x[t] will continue, but that is because you get an interpolating function that will extrapolate outside the known interval.

Best wishes,

Marco

Ammar,

You can print the result. Also, As Marco points out, Since Plot extrapolates beyond the end of your integration (Evaluate sol1 to see this) , you can save the end value and use it in the plot.

I would do:

ode1 = {x'[t] == -1, x[0] == 1, y'[t] + y[t] x[t]^2 == 100, 
   y[0] == 10, 
   WhenEvent[x[t] == 0, "StopIntegration"; 
    Print["EndTime: ", stoptime = t]]};
sol1 = NDSolve[ode1, {x, y}, {t, 0, 10}]; Plot[{x[t] /. sol1}, {t, 0, 
  stoptime}]

Regards,

Neil

Another way would be to do this:

ode1 = {x'[t] == -1, x[0] == 1, y'[t] + y[t] x[t]^2 == 100, 
y[0] == 10, WhenEvent[x[t] == 0, "StopIntegration"]}; sol = NDSolve[ode1, {x, y}, {t, 0, 3}];

Needs["DifferentialEquations`InterpolatingFunctionAnatomy`"];
ParametricPlot[{x[t], y[t]} /. sol, Evaluate[Flatten[{t, InterpolatingFunctionDomain[x /. sol[[1]]][[1]]}]], 
AspectRatio -> 1]

Cheers,

Marco

Many thanks. Your answers were really helpful, “WhenEvent” does it nicely :slight_smile: