1
$\begingroup$

I am trying to solve an optimization problem with complicated constraints which can be computed only numerically. I have written a module that computes lhs of these constraints. Now I need to tell Mathematica that each of these constraints must be less than or equal to 0. I tried using Thread command inside NMinimize, However, Mathematica evaluates thread first and returns an error while substituting numbers. I tried Hold and ReleaseHold within NMinimize as illustrated in other posts, but it did not work out.

I have included a simple and trivial example here. Nevertheless it points to my question,

const[x_?NumericQ] := Module[{ret},
ret = {f[x], f[2*x], f[3*x]};
Return[ret];]

The optimization part

NMinimize[x^2, Thread[const[x] <= 4], {x}]

Returns error:

NMinimize::bcons: The following constraints are not valid: {const[x]<=4}.
Constraints should be equalities, inequalities, or domain specifications involving the variables

$\endgroup$
1
  • $\begingroup$ Try NMinimize[Flatten@{x^2, Thread[const[x] <= 4]}, {x}] instead. In the presence of constraints, NMinimize requires a flat list of equations and constraints as its first argument (see third syntax example in the docs). $\endgroup$
    – MarcoB
    Jun 10, 2016 at 15:30

1 Answer 1

1
$\begingroup$

Do not use the pattern x_?NumericQ when defining const, because you are not using it numerically but symbolically.

f[x_] := 42 + x
const[x_] := {f[x], f[2*x], f[3*x]}
NMinimize[x^2, Thread[const[x] <= 4], {x}]

{1444., {x -> -38.}}

Note that I have removed a lot of unnecessary code from your definition of const.

$\endgroup$
2
  • $\begingroup$ but in my actual problem I cannot evaluate the constraints analytically because it is too complicated. How can I do this numerically? $\endgroup$
    – user40876
    Jun 11, 2016 at 3:49
  • $\begingroup$ The constraints in the original problem cannot be evaluated symbolically, that is why I have used NumericQ in this example. Is it possible to do this numerically and return a result that NMinimize will be able to interpret? $\endgroup$ Jun 11, 2016 at 12:16

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