Skip to main content

RandomSource

Trait RandomSource 

Source
pub trait RandomSource {
    // Required method
    fn next_bits(&mut self, bits: u32) -> i32;

    // Provided methods
    fn next_double(&mut self) -> f64 { ... }
    fn next_int_bounded(&mut self, bound: i32) -> Option<i32> { ... }
    fn next_long(&mut self) -> i64 { ... }
    fn next_prime(&mut self) -> i32 { ... }
    fn next_index(&mut self, size: u64) -> u64 { ... }
}
Expand description

A source of random bits, with the derived draws TLC uses.

Everything TLC draws reduces to java.util.Random.next(bits): nextInt(bound), nextLong and nextDouble are fixed functions of successive next calls. So a source only implements RandomSource::next_bits; the provided methods are Java 17’s algorithms (java/util/Random.java), and give TLC’s values exactly when the bits are JavaRandom’s.

The trait is object safe. Any FnMut(u32) -> i32 is a source, so an evaluator that must not name this crate (dive-eval sits below dive-stdlib in the layering) can carry a &mut dyn FnMut(u32) -> i32 and the operators accept it:

use dive_stdlib::random::{JavaRandom, RandomSource};
let mut rng = JavaRandom::new(7);
let mut bits = |n| rng.next_bits(n);
let f: &mut dyn FnMut(u32) -> i32 = &mut bits;
// RandomElement(1..1000000) with -seed 7, as TLC draws it.
assert_eq!(1 + (f.next_double() * 1_000_000.0).floor() as i64, 730_700);

Required Methods§

Source

fn next_bits(&mut self, bits: u32) -> i32

The next bits random bits (1..=32), as java.util.Random.next(bits): non-negative for bits < 32, any i32 for 32.

Provided Methods§

Source

fn next_double(&mut self) -> f64

Random.nextDouble(): a double in [0, 1) from 53 bits.

Source

fn next_int_bounded(&mut self, bound: i32) -> Option<i32>

Random.nextInt(bound), or None when bound <= 0 (where Java throws IllegalArgumentException). Draws nothing for a bad bound.

Source

fn next_long(&mut self) -> i64

Random.nextLong().

Source

fn next_prime(&mut self) -> i32

RandomGenerator.nextPrime(Random): one of TLC’s 1341 primes near 1.28 million, chosen with one nextDouble.

Source

fn next_index(&mut self, size: u64) -> u64

(int) Math.floor(nextDouble() * size): TLC’s index into a set of size elements (SetEnumValue.randomElement, IntervalValue.randomElement, SimulationWorker.randomState). size 0 gives 0, as in TLC, after drawing.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§