开发者

Maximize function in Mathematica which counts elements

开发者 https://www.devze.com 2023-02-08 08:02 出处:网络
I reduced a debugging problem in Mathematica 8 to something similar to the following code: f = Function[x,

I reduced a debugging problem in Mathematica 8 to something similar to the following code:

f = Function[x,
 list = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5};
 Count[list, x]
];

f[4]
Maximize{f[x], x, Integers]

Output:

4
{0, {x->0}}

So, while the maximum o function f is obtained when x equals 4 (开发者_如何转开发as confirmed in the first output line), why does Maximize return x->0 (output line 2)?


The reason for this behavior can be easily found using Trace. What happens is that your function is evaluated inside Maximize with still symbolic x, and since your list does not contain symbol x, results in zero. Effectively, you call Maximize[0,x,Integers], hence the result. One thing you can do is to protect the function from immediate evaluation by using pattern-defined function with a restrictive pattern, like this for example:

Clear[ff];
ff[x_?IntegerQ] := 
  With[{list = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5}}, Count[list, x]]

It appears that Maximize can not easily deal with it however, but NMaximize can:

In[73]:= NMaximize[{ff[x], Element[x, Integers]}, x]

Out[73]= {4., {x -> 4}}

But, generally, either of the Maximize family functions seem not quite appropriate for the job. You may be better off by explicitly computing the maximum, for example like this:

In[78]:= list = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5};
Extract[#, Position[#, Max[#], 1, 1] &[#[[All, 2]]]] &[Tally[list]]

Out[79]= {{4, 4}}

HTH


Try this:

list = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5};
First@Sort[Tally[list], #1[[2]] > #2[[2]] &]

Output:

{4, 4}
0

精彩评论

暂无评论...
验证码 换一张
取 消