Let's say I have aset = {-1, 0, 2}
. I would like to create a variable Var
that takes values from that set, i.e. var = -1
or var = 0
or var = 2
.
What I'm trying to do is using the variable in NMinimize
as a constraint. A simple example could be as follow:
NMinimize[{a + 1, var == -1 || var == 0 || var == 2, a > 0}, a]
The result is, obviously:
{1., {a -> 0.}}
But if the set is much larger I can't write down constraints for each element. Is there a more efficient way to do this?
Edit
Both answers work (see comments). However, if I change the code a bit,
set = {b^2, b^2 + 1, b^2 - 1};
NMinimize[{a + 1, Or @@ (a == # & /@ set)}, {a, b}]
gives
{-7.45058*10^-9, {a -> -1., b -> -7.43726*10^-9}}`
while
NMinimize[{a + 1, Times @@ ((a - #)& @ set) == 0}, {a, b}]
gives
{-3.53148*10^-9, {a -> -1., b -> -7.29659*10^-9}}
Both results are satisfactorily correct. However I notice that the second result is a little bit more accurate.
NMinimize[{a + 1, {Or @@ (a == # & /@ {-1, 0, 2}) && a > 0}}, a]
? $\endgroup$NMinimize[{a + 1, Times @@ ((a - #) &@{-1, 0, 2}) == 0}, a]
$\endgroup$