# Avoid error when using piecewise function in NDSolve?

**URL:** <https://community.wolfram.com/t/avoid-error-when-using-piecewise-function-in-ndsolve/12421>\
**Category:** Questions\
**Tags:** physics, equation-solving, numerical-computation\
**Created:** [May 4, 2018, 4:24am UTC](https://community.wolfram.com/t/avoid-error-when-using-piecewise-function-in-ndsolve/12421 "2018-05-04T04:24:58Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ywh](https://avatars.discourse-cdn.com/v4/letter/y/a183cd/32.png) [@ywh](https://community.wolfram.com/u/ywh)\
**Post date:** [May 4, 2018, 4:24am UTC](https://community.wolfram.com/t/avoid-error-when-using-piecewise-function-in-ndsolve/12421/1 "2018-05-04T04:24:58Z")

</div>

I am trying to use piecewise function in NDSolve

 ![Screenshot2018-05-0400.25.51.png](https://global.discourse-cdn.com/wolfram/original/3X/1/2/12f9913de56550a2f1f146be880e2363bfafe5ca.png)

but get error message that follows:

 ![Screenshot2018-05-0400.23.09.png](https://global.discourse-cdn.com/wolfram/original/3X/7/a/7a512d0a95432ec9bc52ca48fe04ca6df09c073c.png)

Any idea why? I tried the residue method as specified in warning, but did not get results that make sense. Help is greatly appreciated!!!

---

<div class="post-metadata">

**Author:** ![mariuszi28cg](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/mariuszi28cg/32/308_2.png) [@mariuszi28cg](https://community.wolfram.com/u/mariuszi28cg)\
**Post date:** [May 4, 2018, 8:55am UTC](https://community.wolfram.com/t/avoid-error-when-using-piecewise-function-in-ndsolve/12421/2 "2018-05-04T08:55:38Z")

</div>

Hi

Your **M[r]** function is constantly growing, so it does not have a maximum.

Regards, MI.

---

<div class="post-metadata">

**Author:** ![gianlucagorni](https://avatars.discourse-cdn.com/v4/letter/g/ec9cab/32.png) [@gianlucagorni](https://community.wolfram.com/u/gianlucagorni)\
**Post date:** [May 4, 2018, 11:23am UTC](https://community.wolfram.com/t/avoid-error-when-using-piecewise-function-in-ndsolve/12421/3 "2018-05-04T11:23:30Z")

</div>

With a few `PiecewiseExpand` it gives a solution:

```
Pf[r_, \[Rho]_] := 
  Piecewise[{{K*(\[Rho][r])^(
      5/3), \[Rho][
       r] < \[Rho]low}, {(\[Rho]high*c^2 - 
        K*\[Rho]low^(5/3))/(\[Rho]high - \[Rho]low)*\[Rho][
       r], \[Rho]low <= \[Rho][r] <= \[Rho]high}, {\[Rho][r]*
      c^2, \[Rho][r] > \[Rho]high}}];
MassEqf = (M'[r] == 4 \[Pi] *\[Rho][r]* r^2);
PressureEqf = (\[Rho]'[r] PiecewiseExpand[
      D[Pf[r, \[Rho]], r]/\[Rho]'[r]] == 
    PiecewiseExpand[-((
      G*(M[r] + 4 \[Pi]*r^3*Pf[r, \[Rho]]/c^2)*(\[Rho][r] + 
         Pf[r, \[Rho]]/c^2))/(r^2*(1 - 2*G*M[r]/(r*c^2))))]);

```
