Skip to main content
Explain what evaluate does
Source Link
Sjoerd Smit
  • 24.8k
  • 48
  • 80

A very simple fix for your problem is to prevent f from evaluating without numeric arguments. While I'm at it, I'll also rewrite f in a slightly nicer way:

Clear[f];
f[kk_?NumericQ] := Module[{sol, y},
  sol = First[
    N[NDSolve[{y''[t] == y[t]^2, y[1] == kk, y'[1] == 1}, y, {t, 2}]]
  ];
  y[2] /. sol
];

The _?NumericQ pattern on f prevents the function from evaluating symbolically. In this form, NMinimize and FindMinimum work immediately:

NMinimize[f[x], x]
FindMinimum[f[x], {x, 0}]

Finally, I'd like to point out that your use of Evaluate does nothing in your code. Evaluate is used to override a Hold attribute. For example:

Hold[Range[3], Evaluate[Range[3]]]

A very simple fix for your problem is to prevent f from evaluating without numeric arguments. While I'm at it, I'll also rewrite f in a slightly nicer way:

Clear[f];
f[kk_?NumericQ] := Module[{sol, y},
  sol = First[
    N[NDSolve[{y''[t] == y[t]^2, y[1] == kk, y'[1] == 1}, y, {t, 2}]]
  ];
  y[2] /. sol
];

The _?NumericQ pattern on f prevents the function from evaluating symbolically. In this form, NMinimize and FindMinimum work immediately:

NMinimize[f[x], x]
FindMinimum[f[x], {x, 0}]

A very simple fix for your problem is to prevent f from evaluating without numeric arguments. While I'm at it, I'll also rewrite f in a slightly nicer way:

Clear[f];
f[kk_?NumericQ] := Module[{sol, y},
  sol = First[
    N[NDSolve[{y''[t] == y[t]^2, y[1] == kk, y'[1] == 1}, y, {t, 2}]]
  ];
  y[2] /. sol
];

The _?NumericQ pattern on f prevents the function from evaluating symbolically. In this form, NMinimize and FindMinimum work immediately:

NMinimize[f[x], x]
FindMinimum[f[x], {x, 0}]

Finally, I'd like to point out that your use of Evaluate does nothing in your code. Evaluate is used to override a Hold attribute. For example:

Hold[Range[3], Evaluate[Range[3]]]
Source Link
Sjoerd Smit
  • 24.8k
  • 48
  • 80

A very simple fix for your problem is to prevent f from evaluating without numeric arguments. While I'm at it, I'll also rewrite f in a slightly nicer way:

Clear[f];
f[kk_?NumericQ] := Module[{sol, y},
  sol = First[
    N[NDSolve[{y''[t] == y[t]^2, y[1] == kk, y'[1] == 1}, y, {t, 2}]]
  ];
  y[2] /. sol
];

The _?NumericQ pattern on f prevents the function from evaluating symbolically. In this form, NMinimize and FindMinimum work immediately:

NMinimize[f[x], x]
FindMinimum[f[x], {x, 0}]