# Random sample of big big numbers

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?

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

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


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.

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