6.10.94-stable

Random

Random, part of the util module, is a random generator.

  • Random::new() creates a Random object
  • Random.setSeed(int) sets a seed, beware of the persistence of the Random object (see example)
  • various methods are available to generate different types of random values, from a uniform distribution: int, float, geo
  • normal and gaussian can be used to draw values from.
use util;

fn gen_three(r: Random) {
    for (var i = 0; i < 3; i++) {
        println(r.uniform(0,100));
    }
}

fn main() {
    var R = Random::new();
    R.setSeed(10);
    gen_three(R);
    gen_three(R);
}

greycat run will display 6 different integers. However, re-runnning the program will generate the same sequence.

To save the state across program executions, you can do something like:

use util;

var R: Random?;

@write
fn gen_three() {
    if (R == null) {
        info("setting R");
        R = Random::new();
        R.setSeed(10);
    }
    for (var i = 0; i < 3; i++) {
        println(R.uniform(0,100));
    }
}

fn main() {
    gen_three();
    gen_three();
}

The info command signals the object creation.

Deleting the gcdata directory will remove the saved Random object, and generate the same initial sequence.