Serialize random state/seed?

Jan Wielemaker J.Wielemaker at
Fri Nov 11 10:48:19 CET 2011

Hi Pedro,

Thanks.  Explicit support would be nicer, but this has to do the job for
now.  If it breaks, we try plan B.  As said, this isn't the only place
where SWI-Prolog relies on GMP internals.  I realise I'm asking too much
if I want a public interface for the serialization trick of mpz and mpq
I'm using now.  The only thing I really dislike in current GMP is the
lack of support for trapping allocation errors in a meaningful way :-(

	Cheers --- Jan

On 11/10/2011 11:23 PM, Pedro Gimeno wrote:
> Jan Wielemaker wrote:
>> :-(  The choice for using mpz_t suggests that the state can be seen as
>> one array.  Right?
> No, the choice for using mpz_t is due to historical reasons (the old
> linear congruential generator that I doubt anyone will use nowadays,
> used an mpz_t for its state). When the new RNG infraestructure was
> planned, there was a need for an extra pointer in a way that didn't
> imply losing binary level compatibility, in order to store the state of
> the generator, and the only other pointer available was that in the
> _mp_d member of _mp_seed.
> (peeks at the code...)
> You're actually lucky that someone included the size in the _mp_alloc
> field of the struct, as my original patch didn't :)
> For the Mersenne Twister generator (currently the default one), the
> pointer in the _mp_d member points to a gmp_rand_mt_struct. As can be
> seen in randmt.h, it doesn't contain any further pointers. It contains
> an array of 624 gmp_uint_least32_t values, and one int with a value that
> ranges from 0 to 623. Size of int can vary, and gmp_uint_least32_t
> probably can too, therefore taking the content as-is might not be a good
> idea if the intention is to save/restore it in a portable way. For MT,
> for cross-platform serialization purposes, I would include two bytes
> with the integer and 624*4 bytes with the array; a total of 2498 bytes
> of serial data.
> In the case of a linear congruential generator, the state pointer points
> to a gmp_rand_lc_struct structure, which in turn contains two mpz_t's
> with their respective pointers and allocations. If you also want to
> support the LCG, good luck...
> If you want to add support for the Mersenne Twister generator, I'd
> advise you to explicitly request it, as opposed to a default generator,
> in order to be safer against compatibility issues that could arise with
> potential future versions of GMP, in case the default generator changes.
> But keep in mind that you'd be relying on GMP internals that are not
> guaranteed to not change. That's a very bad idea.
> For best guarantees of compatibility with future versions, the best
> advice I can give is to throw away GMP's random generation functions and
> create your own generator that yields mpz's.
> Hope that helps.
> -- Pedro Gimeno

More information about the gmp-discuss mailing list