6
$\begingroup$

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

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

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]}]

enter image description here

$\endgroup$
  • 2
    $\begingroup$ 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] $\endgroup$ – J. M. will be back soon Aug 1 at 13:33
  • $\begingroup$ How about if i want to do that in sine curve? $\endgroup$ – Math Aug 2 at 13:07
  • $\begingroup$ @Math Something like Select[p, #[[2]] <Sin[ #[[1]] ] &] $\endgroup$ – Ulrich Neumann Aug 2 at 13:13
9
$\begingroup$
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}

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

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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