1
$\begingroup$

I wrote a complex constraint condition for my problem. I have a simple version of my code:

c[x_] := If[x >= 20, True, False];
FindMinimum[{x^2, c[x] == True}, x]
NMinimize[{x^2, c[x] == True}, x]

Functions FindMinimum and NMinmize didn't work. I can't see why?


Update

c[x_] := If[x >= 20, True, False];
FindMinimum[{x^2, c[x] }, x]
NMinimize[{x^2, c[x] }, x]

It works well, but I can't still solve my problem. I constructed another example:

c[x_] := Module[{}, Print[x]; True];
FindMinimum[{x^2, c[x]}, x]
NMinimize[{x^2, c[x]}, x]

x
{0., {x -> 0.}}

Why Print[x] didn't output the value of x?

$\endgroup$
  • $\begingroup$ @AlexeyPopkov this is just an example. Actually I want a much more complex constraint condition which must be an Module $\endgroup$ – huangbiubiu Sep 10 '16 at 8:40
  • $\begingroup$ Print[x] didn't output the value of x because x had no value at the time Print[x] was evaluated. $\endgroup$ – m_goldberg Sep 10 '16 at 15:41
2
$\begingroup$

Simply use FindMinimum[{x^2, x >= 20}, x]. Or if you insist on a function,

Clear[c]
c[x_] := If[x >= 20, True, False];
FindMinimum[{x^2, c[x]}, x]
NMinimize[{x^2, c[x]}, x]
{400., {x -> 20.}}

{400., {x -> 20.}}

For printing intermediate numerical values it is recommended to use EvaluationMonitor:

FindMinimum[{x^2, c[x]}, x, EvaluationMonitor :> Print[x]]
NMinimize[{x^2, c[x]}, x, EvaluationMonitor :> Print[x]]
$\endgroup$
  • $\begingroup$ In my example this work well, but my problem is still can't be solved. I update my post $\endgroup$ – huangbiubiu Sep 10 '16 at 8:50
  • $\begingroup$ @YuhengHuang Regarding your Update: you problem is very similar to this and is explained in this comment. But the solution is different: use EvaluationMonitor for printing intermediate numerical values. Updated the answer. $\endgroup$ – Alexey Popkov Sep 10 '16 at 8:56

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