m = 20;
n = 4;
binlims = {0, 2, 9, 14, 20};
binlengths = Differences[binlims];
RandomChoice
SeedRandom[1]
rc = RandomChoice[binlengths -> Range[4], 20]
{4, 2, 4, 2, 2, 1, 3, 2, 2, 4, 2, 4, 2, 2, 4, 4, 4, 3, 2, 2}
WeightedData + EmpiricalDistribution + RandomVariate
SeedRandom[1]
rved = RandomVariate[EmpiricalDistribution[WeightedData[Range[4], binlengths]], 20]
{4, 2, 4, 2, 2, 1, 3, 2, 2, 4, 2, 4, 2, 2, 4, 4, 4, 3, 2, 2}
UniformDistribution + TransformedDistribution + RandomVariate
This mimics the description of the process used to generate the random variable X
, but it is much slower than the previous two methods.
ClearAll[pw]
pw[x_] := Piecewise[MapIndexed[{#2[[1]], #} &, #] &@(# <= x < #2 & @@@
Partition[binlims, 2, 1])];
pw[x]
$\begin{cases}
1 & 0\leq x<2 \\
2 & 2\leq x<9 \\
3 & 9\leq x<14 \\
4 & 14\leq x<20
\end{cases}$
SeedRandom[1]
rvtd = RandomVariate[TransformedDistribution[pw[x],
Distributed[x, UniformDistribution[{0, m}]]], 20]
{4, 2, 4, 2, 2, 1, 3, 2, 2, 4, 2, 4, 2, 2, 4, 4, 4, 3, 2, 2}
When used with the same RandomSeed
all three methods give the same result. The first two are roughly equal in terms of speed.
rc == rved == rvtd
True
Differences
andRandomChoice
(with weights). $\endgroup$RandomChoice
, I think that will work. $\endgroup$