2
$\begingroup$

I run the following code and I got what I want

a = Table[
   EuclideanDistance[RandomVariate[UniformDistribution[]], 
    RandomVariate[UniformDistribution[]]], 1000];
Length[Select[a, # < 0.5 &]]

I don't know why when I run

Count[a,# < 0.5 &]

I got 0, shouldn't Count[a,# < 0.5 &]=Length[Select[a, # < 0.5 &]]?

$\endgroup$

3 Answers 3

5
$\begingroup$

The second arg of Count expects a pattern, not a function. You could use either or the following:

In[29]:= Count[a, _?(# < 0.5 &)]

Out[29]= 763

In[30]:= Count[a, x_ /; x < 0.5]

Out[30]= 763
$\endgroup$
3
$\begingroup$

Help says Count argument should be a pattern.

So do this

Count[a, x_ /; (x < 0.5)]

Mathematica graphics

# < 0.5 & is not a pattern. It is a function.

$\endgroup$
1
$\begingroup$

You can also use the CountsBy function, where you can use a test directly:

{f, t} = Values@CountsBy[a, # < 0.5 &]

{246, 754}

$\endgroup$

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