How big is the Perl rand argument?

rand(n)returns the number between 0and n. Will it randwork as expected with respect to "randomness", for all arguments up to an integer limit on my platform?

+5
source share
3 answers

This will depend on your value randbits:

rand calls your system random number generator (or whatever Perl is compiled into your copy). For this discussion, I will call it a RAND generator to distinguish it from rand, the Perl function. RAND produces an integer from 0 to 2 ** randbits - 1, inclusive, where randbits is a small integer. To find out what it is in your perl, use the perl -V: randbits command. Common values: 15, 16 or 31.

When you call rand with the arg argument, perl takes this value as an integer and evaluates that value.

                        arg * RAND
          rand(arg) = ---------------
                        2**randbits

This value will always be in the required range.

          0  <=  rand(arg)  < arg

arg 2 ** randbits,    . , randbits = 15, RAND     0..32767. , , RAND, 32768     . , rand (arg), 32768     .

+8

, ().

perl -V:randbits

use Config;
my $randbits = $Config{randbits};

rand 2 ^ randbits . , 2 ^ randbits, [0, N), N > 2 ^ randbits.

N, , , ( ) . , .

, randbits - 15 Windows. , 32768 (2 ** 15) . , rand :

use Config;
use constant RANDBITS => $Config{randbits};
use constant RAND_MAX => 2**RANDBITS;

sub double_rand {
    my $max = shift || 1;
    my $iv  =
          int rand(RAND_MAX) << RANDBITS
        | int rand(RAND_MAX);
    return $max * ($iv / 2**(2*RANDBITS));
}

, randbits = 15, double_rand randbits = 30, 1073741824 (2 ** 30) . ( ) , .

+2

We are talking about large random integers and whether they can be obtained. It should be noted that the concatenation of two random integers is also a random integer. Therefore, if for some reason your system cannot go beyond 999999999999, just write

$bigrand = int(rand(999999999999)).int(rand(999999999999));

and you get a random integer (maximum) twice the length.

(Actually, this is not a numerical answer to the question "how big can a rand number be," but rather the answer "you can get as much as you want, just concatenate small numbers.")

0
source

All Articles