# How to count points under the curve?

I need a formula to calculate how many points are there under the curve $$y=x$$.

• Some related: (97299), (157149), (181620)...I think there's more, but couldn't find the right search terms. – Michael E2 Aug 1 '19 at 20:46

Try

p = RandomReal[{0, 1}, {50, 2}]
pu=Select[p, #[[2]] < #[[1]] &]
Length[pu] (* number of points yi<xi*)

Show[{Plot[x, {x, 0, 1}], ListPlot[p],ListPlot[pu, PlotStyle -> Red]}]


• One could also use pu = Select[p, Apply[Greater]] in this case. A slower, but generalizable approach would be rmf = RegionMember[ImplicitRegion[y <= x, {x, y}]]; pu = Select[p, rmf] – J. M. will be back soon Aug 1 '19 at 13:33
• How about if i want to do that in sine curve? – Math Aug 2 '19 at 13:07
• @Math Something like Select[p, #[[2]] <Sin[ #[[1]] ] &]  – Ulrich Neumann Aug 2 '19 at 13:13
p = RandomReal[{0, 1}, {50, 2}]
Count[p, {x_, y_} /; y < x]


This is many times more efficient for long lists:

Total[UnitStep[Subtract @@ Transpose[p]]]


# Edit:

A few timings under version 12.0 on macos:

p = RandomReal[{0, 1}, {1000000, 2}];
Length[Select[p, #[[2]] < #[[1]] &]] // RepeatedTiming
Count[p, {x_, y_} /; y < x] // RepeatedTiming
Total[UnitStep[Subtract @@ Transpose[p]]] // RepeatedTiming


{1.31, 499894}

{0.757, 499894}

{0.0089, 499894}

• Very interesting alternatives. By the way the last one is the slowest (MMA v.11.0.1) – Ulrich Neumann Aug 1 '19 at 14:19
• @UlrichNeumann Really? That is indeed surprising... Unfornately, I cannot test it under v. 11.0.1; I have removed it recently. – Henrik Schumacher Aug 1 '19 at 16:26
• Similar timings under v10.4 and 11.3. – corey979 Aug 1 '19 at 16:33
• @UlrichNeumann That is surprising. What if you try the compiled version Compile[{{p,_Real,2}},Total[UnitStep[p.{1,-1}]]]? – Silvia Aug 2 '19 at 3:20
• @Silvia Great idea to use Dot! And I am also surprised that Compile makes a difference here. – Henrik Schumacher Aug 2 '19 at 3:21

You can use RegionMember for this:

reg = RegionMember[ImplicitRegion[y<x, {x,y}]];

Tally @ reg[p]


{{False, 23}, {True, 27}}

This will not be as fast as Henrik's answer.