in reply to Randomizing Large Integers

Is 32K a limitation of the standard rand function? I figured that in my installation (v5.8.8 built for i486-linux-gnu-thread-multi) rand works for given numbers up to 2**32. But I couldn't find any documentation for the limit. A 32 bit limitation seems logical, however. In my case I needed random hex numbers with 2**N limits, so I just concatenated multiple rand calls using printf. On Linux you also can read from /dev/urandom to get random bytes.

Replies are listed 'Best First'.
Re^2: Randomizing Large Integers
by almut (Canon) on May 19, 2008 at 19:48 UTC
    Is 32K a limitation of the standard rand function?

    The macro (uconfig.h, line 3368 in 5.8.8 or 4057 in 5.10.0) looks like only 15 bits are being used:

    #define Drand01() ((rand() & 0x7FFF) / (double) ((unsigned long)1 << +15)) ^^^^

    Update: though, a somewhat closer look suggests this might be configuration dependent (at least, Configure checks for drand48()), so maybe I spoke too soon...

    Update2: just ran a test build on a system which has drand48()... et voila, the macro ends up being defined as

    #define Drand01() drand48()

    So, as often, the answer is: it depends :)

      15 bit of the input or of the output?

      I get the following behavior that lets me assume that 32 bit random integers work:

      # perl -e 'printf "%010x\n", int rand 2**16' 00000052e2 # perl -e 'printf "%010x\n", int rand 2**32' 006f7ae0c5 # perl -e 'printf "%010x\n", int rand 2**64' 00ffffffff

      i.e. rand 2**N seems to return a N bit random integer, up to N = 32 but not above.

        15 bit of the input or of the output?

        15 bits of entropy. For a given argument, rand will only spit out 215 different results (spread over the requested range).
Re^2: Randomizing Large Integers
by hangon (Deacon) on May 19, 2008 at 20:23 UTC

    From what I've read, rand is dependent on whats installed on the OS. On this system, when feeding rand with integers > 32768, the distribution of values returned (from multiple calls using the same number) breaks down badly. So this seems to support 15 bits.

      Running perl -V:randbits will tell you how many random bits your perl's rand() has.

      Cheers,
      Rob