6
$\begingroup$

I have a Mathematica assignment where we need to solve a modeling population growth enter image description here

I have managed to come up with this for the representation of the equation in Mathematica:

    ClearAll[t, k, r, n]
Manipulate[
 Plot[p[t] /. psol, {t, 0, 20}], {{n, 0.5, "Start population"}, 
  0.5, 10}, {{k, 1, "Max population"}, 1, 
  20}, {{r, 2, "Speed"}, 2, 4},
 Initialization :> (psol = 
     DSolve[{p'[t] == r*p[t] (1 - p[t]/k), p[0] == n}, p[t], t];)]

Can anyone tell me what I am doing wrong? I am new to Mathematica.

$\endgroup$
  • $\begingroup$ try replacing psol with psol[n_, k_, r_, t_] $\endgroup$ – user42582 Nov 22 '17 at 18:22
5
$\begingroup$

The reason why the plot doesn't update when parameters change is because of the evaluation order. Inside your Initialization expression, the first thing that happens is that r, k and n get replaced by the respective start values of the Manipulate parameters. Thus psol never contains a general solution, but just a specialized version for the initial values, which leads to the plot never updating.

One way of solving it is to use slightly different names in the general solution and use replacement rules to have exact control when the manipulate values should be injected:

ClearAll[t, k, r, n]
Manipulate[
  Plot[p[t] /. psol /. {rr -> r, kk -> k, nn -> n}, {t, 0, 20}, PlotRange -> {0, k}]
  , {{n, 0.5, "Start population"}, 0.5, 10}
  , {{k, 1, "Max population"}, 1, 20}
  , {{r, 2, "Speed"}, 2, 4}, 
  Initialization :> (psol = DSolve[{p'[t] == rr*p[t] (1 - p[t]/kk), p[0] == nn}, p[t], t];)
]
$\endgroup$
5
$\begingroup$

It can also be done this way.

Manipulate[
  Plot[Evaluate[pF[k, r, n][t]], {t, 0, 5}, PlotRange -> {0, k}],
  {{n, 1, "Start population"}, 1, 10, 1, AppearanceElements -> All},
  {{k, 1, "Max population"}, 1, 50, 1, AppearanceElements -> All},
  {{r, 2, "Speed"}, 2, 4, AppearanceElements -> All},
  Initialization :> (
    pF[k_, r_, n_] = DSolveValue[{p'[t] == r p[t] (1 - p[t]/k), p[0] == n}, p, t])]

demo

Personally, I find DSolveValue easier to use than DSolve in situations like this one.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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