Mathematica's Minimize function
Is it true that Mathematica's Minimize
function does not allow constraints like Mod[x,2]==0? I am tr开发者_开发问答ying to solve a MinuteMath puzzle with Mathematica:
What is the smallest possible average of four distinct positive even integers?
My "solution" looks like this:
vars = Subscript[x, #] & /@ Range[4];
cond = Apply[And, Mod[#, 2] == 0 & /@ vars] &&
(0 < Subscript[x, 1]) &&
Apply[And, Table[Subscript[x, i] < Subscript[x, i + 1], {i, 1, 3}]];
Minimize[{Mean[vars], cond}, vars, Integers]
but Minimize
returns unevaluated. Additional question: Can I use EvenQ
for defining the constraints? Problem is, EvenQ[x]
returns False
for undefined expressions x
.
Clearly, this doens't require Mathematica but, in answer to your question, it seems that Minimize
doesn't like the mods. You could build it into the forumula, though, like so:
Minimize[{(2 x1 + 2 x2 + 2 x3 + 2 x4)/4,
0 < x1 < x2 < x3 < x4}, {x1, x2, x3, x4}, Integers]
A clear overkill for this problem, but useful to show some tricks.
Note that:
Exists[x, Element[x, Integers] && n x == y]
can be used as an alternative to
Mod[y,n] == 0
So:
Minimize[{(x1 + x2 + x3 + x4)/4, 0 < x1 < x2 < x3 < x4 &&
Exists[x, Element[x, Integers] && 2 x == x1] &&
Exists[x, Element[x, Integers] && 2 x == x2] &&
Exists[x, Element[x, Integers] && 2 x == x3] &&
Exists[x, Element[x, Integers] && 2 x == x4]
},
{x1, x2, x3, x4}, Integers]
-> {5, {x1 -> 2, x2 -> 4, x3 -> 6, x4 -> 8}}
Or perhaps more elegant:
s = Array[x, 4];
Minimize[{
Total@s,
Less @@ ({0} \[Union] s) &&
And @@ (Exists[y, Element[y, Integers] && 2 y == #] & /@ s)},
s, Integers]
--> {20, {x[1] -> 2, x[2] -> 4, x[3] -> 6, x[4] -> 8}}
Minimize is not good for this question, it gives a wrong solution:
2 4 8 10
The good solution is:
2 4 6 12
"Select" accept Mod function it's better than Minimize
Minimize gives the wrong solution.
Play this programe and see:
Res=Select[Permutations[Range@20 {4}],Mod[ #[[1]],2]==0 &&Mod[ #[[2]],2]==0&&Mod[#[[3]],2]==0 &&Mod[#[[4]],2]==0&&Mod[(#[[1]]+#[[2]]+#[[3]]+#[[4]])/4,2]==0 &];Sort[Res,Less];Res[[1]]
精彩评论