# NDSolve swapping between solution branches to stay positive

I have a differential equation that I wish to solve, with the requirement that my independent variable must stay positive, but do not require it to remain differentiable. My equation comes from minimising a (constrained) variational principle using calculus of variations.

An example equation is:

DSolve[{z[s] (s - z[s] z''[s] - z'[s]^2) == 0, z, s]


which has three solutions:

$$z = 0, \pm \frac{\sqrt{s^3 + 6 C_1 + 3 s C_2}}{\sqrt{3}}$$

For some values of the boundary conditions, one of the non-zero roots will provide a solution which becomes imaginary at an interior point. At this point, I need the $z=0$ solution to be chosen, then swap back to the solution which satisfies the boundary conditions once it is real again. For instance, $z(0)=1,z(3)=2$ shows this behaviour.

How do I automate this? Note that I can't use NDSolve on the equation above, as it gets upset due to the presence of the z[s] term, and also that this degenerate condition may not be just $z=0$ in my actual example, it can be any non-differential equation involving $s$ and $z$. So this fails:

NDSolve[{z[s] (s - z[s] z''[s] - z'[s]^2) == 0, z[0] == 1,   z[3] == 2}, z, s]


Solutions using only DSolve are not going to work for more complicated equations (like my real ones).

• So, you can't use NDSolve and you can't use DSolve? That's a problem. I think without further context, this is hard to answer. For instance, what are you doing with these solutions? You said you are varying boundary conditions, but in what context? Do you just need it to spit back a solution, either 0 or one of the others, based on the choice of BC? Or are you constructing a function of the BC, etc. More info please! Jul 22 '16 at 20:49
• How about you remove the offending z[s], use NDSolve, get a solution, return the solution if it's real and 0 if it's complex? Jul 22 '16 at 20:51

y[s] == z[s]^2