Allison Randal > parrot > Math/rand.pir

Download:
parrot-1.0.0.tar.gz

Annotate this POD

Website

View/Report Bugs

Source  

NAME ^

Math/rand.pir - the ANSI C rand pseudorandom number generator

DESCRIPTION ^

The rand function computes a sequence of pseudo-random integers in the range 0 to RAND_MAX.

The srand function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand. If srand is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated. If rand is called before any calls to srand have been made, the same sequence shall be generated as when srand is first called with a seed value of 1.

Portage of the following C implementation, given as example by ISO/IEC 9899:1999.

  static unsigned long int next = 1;
  //
  int rand(void)
  {
      next = next * 1103515245 + 12345;
      return (unsigned int)(next/65536) % 32768;
  }
  //
  void srand(unsigned int seed)
  {
      next = seed;
  }

USAGE ^

    load_bytecode 'library/Math/Rand.pbc'
    .local pmc rand
    rand = get_global [ 'Math'; 'Rand' ], 'rand'
    .local pmc srand
    srand = get_global [ 'Math'; 'Rand' ], 'srand'
    .local int seed
    srand(seed)
    $I0 = rand()
    .local pmc rand_max
    rand_max = get_global [ 'Math'; 'Rand' ], 'RAND_MAX'
    .local int RAND_MAX
    RAND_MAX = rand_max()

AUTHORS ^

Francois Perrad