5
$\begingroup$

Screen Shot of my Mathematica Commands

I was using RandomSample with very skewed weights. I am asking for a random sample of 6 numbers 1 through 100 without replacement. In the screen shown, the weights for 1 through 6 are 100 000, with all others less then 1; hence, the RandomSample should return numbers 1 through 6 is a random order very very often. But it does not.

I have copied and pasted the commands shown.

Am I missing something? Or am I misunderstanding the RandomSample function? Or is this actually a bug?

$\endgroup$
  • 7
    $\begingroup$ Please do not post images as code. Read the formatting FAQ in the Help section, and post actual code. $\endgroup$ – ciao Mar 5 '14 at 3:03
4
$\begingroup$

Definitely something interesting going on here.

c[x_] := Count[Table[RandomSample[{100000, 0, 1} -> {1, 2, 3}, 1], {x}], {3}]

DiscretePlot[c[x]/x, {x, 10, 400}]

enter image description here

Note that changing the zero weight to something greater than zero seems to give the expected behavior. Some experimentation seems to suggest that adding a zero weight in the presence of weights with large difference in scale causes other weights to be treated as equal.

I also notice that even when the weights are in the same ballpark odd stuff happens when we cross the 249 to 250 replication mark.

c2[x_] := Count[Table[RandomSample[{2, 0, 1, 2} -> {1, 2, 3, 4}, 1], {x}], {3}]
DiscretePlot[c[x]/x, {x, 10, 400}]

enter image description here

$\endgroup$
  • 1
    $\begingroup$ It is clearly documented "The weights must be positive...", emphasis mine. $\endgroup$ – ciao Mar 5 '14 at 3:35
  • 4
    $\begingroup$ The threshold of 250 is likely due to auto-compilation in Table (which kicks in at precisely 250). $\endgroup$ – Szabolcs Mar 5 '14 at 3:41
  • 1
    $\begingroup$ This would explain why weights can't be zero, but if it's really so by design, RandomSample should give a warning, the same as it warns about negative weights. $\endgroup$ – Szabolcs Mar 5 '14 at 3:48
  • 1
    $\begingroup$ The weird behaviour at 250 is only with RandomSample, not RandomChoice, and only with integer weights, not with floating point weights. $\endgroup$ – Szabolcs Mar 5 '14 at 3:50
  • $\begingroup$ @Szabolcs I suspected auto-compilation as well. $\endgroup$ – Andy Ross Mar 5 '14 at 14:12

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.