12.5 C++ Interface Random Numbers

Class: gmp_randclass

The C++ class interface to the GMP random number functions uses gmp_randclass to hold an algorithm selection and current state, as per gmp_randstate_t.

Function: gmp_randclass::gmp_randclass (void (*randinit) (gmp_randstate_t, …), …)

Construct a gmp_randclass, using a call to the given randinit function (see Random State Initialization). The arguments expected are the same as randinit, but with mpz_class instead of mpz_t. For example,

gmp_randclass r1 (gmp_randinit_default);
gmp_randclass r2 (gmp_randinit_lc_2exp_size, 32);
gmp_randclass r3 (gmp_randinit_lc_2exp, a, c, m2exp);
gmp_randclass r4 (gmp_randinit_mt);

gmp_randinit_lc_2exp_size will fail if the size requested is too big, an std::length_error exception is thrown in that case.

Function: gmp_randclass::gmp_randclass (gmp_randalg_t alg, …)

Construct a gmp_randclass using the same parameters as gmp_randinit (see Random State Initialization). This function is obsolete and the above randinit style should be preferred.

Function: void gmp_randclass::seed (unsigned long int s)
Function: void gmp_randclass::seed (mpz_class s)

Seed a random number generator. See see Random Number Functions, for how to choose a good seed.

Function: mpz_class gmp_randclass::get_z_bits (mp_bitcnt_t bits)
Function: mpz_class gmp_randclass::get_z_bits (mpz_class bits)

Generate a random integer with a specified number of bits.

Function: mpz_class gmp_randclass::get_z_range (mpz_class n)

Generate a random integer in the range 0 to n-1 inclusive.

Function: mpf_class gmp_randclass::get_f ()
Function: mpf_class gmp_randclass::get_f (mp_bitcnt_t prec)

Generate a random float f in the range 0 <= f < 1. f will be to prec bits precision, or if prec is not given then to the precision of the destination. For example,

gmp_randclass  r;
mpf_class  f (0, 512);   // 512 bits precision
f = r.get_f();           // random number, 512 bits