One has a (system) of ODEs with a one-parameter family of initial conditions. For example,
f[kk_] := N[aa = kk; s = NDSolve[{y''[t] == y[t]^2, y[1] == aa, y'[1] == 1},
y, {t, 2}]; Evaluate[(y[2] /. s)][[1]]]
where k
is the parameter, and one sees $f(k)$ as a function of $k$ works fine, as one can try to plot
Plot[f[x], {x, -3, 0}]
and obtain
However, when one tries to find the min, using FindMinimum
or NMinimize
, it does not work as it seems Mathematica would first perform symbolic calculation with
NDSolve[{(y''[t] == -2y[t], y[1] == x, y'[1] == 1}, y, {t, 2}]
which results an error as the initial condition is not a number, and returns y[2.]
before continuing evaluating NMinimize[y[2.], x]
.
Does anyone know how to get around it, or some better ways to do the optimization?
Answer
Use ParametricNDSolve
or it's cousin ParametricNDSolveValue
:
s = ParametricNDSolveValue[
{y''[t] == y[t]^2, y[1] == aa, y'[1] == 1},
y[2],
{t, 2},
aa
];
NMinimize[s[aa], aa]
{0.0964433, {aa -> -1.65429}}
Comments
Post a Comment