1
$\begingroup$

I am trying to create a function s[n_] which returns a subset of $\{ 1,2,3 \dots n\}$ wherein each integer $j$ appears with probability $1/j$; ie. there is a $1/4$ chance that $4$ belongs to s[i] for $i \geq 4$.

The only way I can think of doing this is actually assembling a list of lists where sets containing, say, $4$, appear $1/4$ of the time. But certainly there is a built-in function for discrete random variables with specified probabilities? I would guess so, but I couldn't find one.

$\endgroup$
1
  • 3
    $\begingroup$ You picked the better answer. So sometimes it's better to wait a day (or more) rather than pick the first answer given. $\endgroup$ Commented Nov 5, 2020 at 17:13

2 Answers 2

3
$\begingroup$

Here is an implementation that is not only more concise, but also 10x faster:

s[n_]:=Select[ Range[n], RandomReal[] < 1/# &] 
$\endgroup$
1
  • 1
    $\begingroup$ +1 Yes, much better! $\endgroup$ Commented Nov 5, 2020 at 16:03
3
$\begingroup$

I assume from what you describe the number 1 is always returned (as its probability of being selected is 1).

SeedRandom[12345] s[n_] := Module[{list}, list = (RandomVariate[BernoulliDistribution[1/#], 1][[1]] & /@ Range[n]) Range[n]; Select[list, # != 0 &]] s[5] (* {1, 4} *) s[20] (* {1} *) s[4] (* {1,3,4} *) 
$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.