I need to randomize large integers (> 32K). I looked at some modules, but I just need to call $foo = rand $bar repeatedly without setting up objects & parameters. So, I came up with the following scheme to extend the range of rand to around 1G. Basically, it breaks $bar into blocks of nearly equal size (within +1 -0) and calls rand twice, once to select a block, and again to select the number within the block, then it totals everything up. It appears to DWIM and seems a reasonable approximation of rand (the distribution of numbers generated compares closely to rand), but I don't have the expertize to test it rigorously.

It's to be used for simulation, and doesn't need to be perfect. Does this seem like a reasonable approach? Am I overlooking any potential problems?

sub bigrand{ my $in = shift; my $limit = 32768; if ($in <= $limit){ return int rand $in; } my $blockSize = int($in ** .5); my $blockSelect = int rand int ($in/$blockSize); my $leftOver = $in % $blockSize; if ($blockSelect < $leftOver){ return ($blockSelect * ($blockSize + 1)) + int rand ($blockSize + 1); }else{ return ($leftOver * ($blockSize + 1)) + (($blockSelect - $leftOver) * $blockSize) + int rand ($blockSize); } }

Update: It's been an education. Up to now, rand is one of those functions I've just used and taken for granted. Thanks especially to BrowserUK for the explanation and links to other nodes, and to tachyon-II whose module Math::Random::MT::Perl I ended up using.


In reply to Randomizing Large Integers by hangon

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.