Hi folks,

For those who work on the Moses code and need to generate
(pseudo-)random numbers sometimes, there's a new module that takes away
some of the drudgery: util/random.cc and util/random.hh.

It has simple templated wrappers for the built-in random()/srandom() and
rand/srand(), to let you generate random values for integer or
floating-point types.  Unlike the built-in functions, they are
thread-safe on all platforms.  So I would like to ask everyone who was
going to use rand()/srand()/random()/srandom() to use this new module
instead.

The functions support a few different uses that I found in the codebase:
random nonnegative value less than n, random nonnegative value less than
or equal to n, random value no less than m but less than n, or random
value no less than m but less than or equal to n.

These are all templates, so you can call them like:

  rand<int>();                  // Random int in [0, RAND_MAX].
  rand_incl<float>(10);         // Random float in [0, 10].
  rand_excl<long>(-10, 10);     // Random long in [-10, 9].

If you don't feel like specifying the type, you can let the template
derive one:

  rand_incl(10.0f);             // Random float in [0, 10].
  rand_excl(5);                 // Random int in [0, 5).

There's a similar family of functions wide_rand() etc.  These are for
integer types only.  For types that are the same width as an int
(typically 32 bits) these functions work just like their non-wide
counterparts.  But for wider types, they combine multiple random numbers
to fill the entire value: a wide_rand<uint64_t>() will combine two
random ints.

These functions are not perfect, so if you need to use them, please have
a look at the documentation in util/random.hh.  There's been a
long-standing desire for a better randomizer, such as the ones in Boost
or C++11, and maybe having all randomizer code in one place will make it
a little easier to insert a replacement.


Jeroen
_______________________________________________
Moses-support mailing list
[email protected]
http://mailman.mit.edu/mailman/listinfo/moses-support

Reply via email to