5
$\begingroup$

Consider the following piece of code:

m = 2;
n = 6;
samplesize = 1000;
totalsize = 2^(n^m);
numbersample = 2 RandomSample[Range[totalsize/2], samplesize];

With this I want to get a RandomSample of samplesize even numbers between 1 and totalsize. I am getting the error SystemException["MemoryAllocationFailure"], due to the size of the list Range[totalsize/2] (although the size of the sample I need is small). How can I modify my code to run within my memory and get the same (maybe) result?

$\endgroup$
8
  • 2
    $\begingroup$ RandomInteger[{1, 2^(6^2 )}, 1000]? $\endgroup$
    – Kuba
    Commented Apr 24, 2018 at 11:02
  • 2
    $\begingroup$ subtle difference, RandomSample ensures no repeats. RandomInteger could repeat with extremely small probability with these numbers. $\endgroup$
    – george2079
    Commented Apr 24, 2018 at 11:27
  • $\begingroup$ @Kuba yeah..... $\endgroup$
    – Filburt
    Commented Apr 24, 2018 at 12:08
  • $\begingroup$ @george2079 That's right, with this size of set I shouldn't worry about repetitions... $\endgroup$
    – Filburt
    Commented Apr 24, 2018 at 12:08
  • 3
    $\begingroup$ You can use Span to avoid the blowup from Range: RandomSample[1 ;; totalsize/2, samplesize] $\endgroup$ Commented Apr 24, 2018 at 14:18

2 Answers 2

8
$\begingroup$

You can use Span to avoid the blowup from Range:

m = 2;
n = 6;
samplesize = 10;
totalsize = 2^(n^m);
numbersample = 2 RandomSample[1 ;; totalsize/2, samplesize]

(* Out[145]= {27031562174, 37752159722, 45591082014, 64125204586, \
66565096356, 29240167748, 42466822774, 11081960620, 37360181228, \
31719722938} *)
$\endgroup$
4
$\begingroup$

You could experiment a bit with the following function

randomSampleOfRange = 
 Compile[{{totalsize, _Integer}, {samplesize, _Integer}},
  Block[{rand, a},
   rand = Table[RandomInteger[{1, (totalsize - i)}], {i, 0, samplesize - 1}];
   Do[
    a = rand[[i]];
    Do[If[rand[[j]] <= a, a++];, {j, 1, i - 1}];
    rand[[i]] = a;
    rand[[1 ;; i]] = Sort[rand[[1 ;; i]]];
    ,
    {i, 2, Length[rand]}];
   rand
   ]
  ]

Use it like this

m = 2;
n = 6;
samplesize = 1000;
totalsize = 2^(n^m);
numbersample = 2 randomSampleOfRange[Quotient[totalsize, 2], samplesize];

I am not entirely sure that the function randomSampleOfRange works as intended, so please tell me if you experience any oddities.

$\endgroup$
2
  • $\begingroup$ That worked absolutely well (using numbersample = 2 randomSampleOfRange[totalsize/2, 1000]), also with greater values. Thanks! $\endgroup$
    – Filburt
    Commented Apr 24, 2018 at 12:07
  • 1
    $\begingroup$ I am glad to hear that. You're welcome! $\endgroup$ Commented Apr 24, 2018 at 12:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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