# 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 == 1,   z == 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! – march 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? – march Jul 22 '16 at 20:51

For the example problem, you can get a result that may be what you are seeking by a change of variable.

y[s] == z[s]^2
Table[D[%, {s, n}], {n, 0, 2}]
Append[%, z[s] (s - z[s] z''[s] - z'[s]^2) == 0]
Eliminate[%, Table[D[z[s], {s, n}], {n, 0, 2}]]
Assuming[y[s] != 0 && y'[s] != 0, FullSimplify[%]]
DSolve[{%, y == 1, y == 4}, y, s]
Plot[Sqrt[y[s]] /. %, {s, 0, 3}]


## • I have actually used y=z^2 to get to this point, my initial variational principle is in terms of y, but I want to restrict y to be positive. – KraZug Jul 25 '16 at 9:38