# Is there a discrete random variable function with which I can specify the probability of returning a value?

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.

• You picked the better answer. So sometimes it's better to wait a day (or more) rather than pick the first answer given.
– JimB
Nov 5, 2020 at 17:13

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

s[n_]:=Select[
Range[n],
RandomReal[] < 1/# &]

• +1 Yes, much better!
– JimB
Nov 5, 2020 at 16:03

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} *)