6 releases (stable)

1.3.0 Mar 18, 2021
1.2.0 Jun 20, 2020
1.1.0 Jun 16, 2020
1.0.1 Jun 15, 2020
0.0.1 Jun 14, 2020

#1366 in Algorithms

Download history 7167/week @ 2024-01-05 7911/week @ 2024-01-12 4540/week @ 2024-01-19 2548/week @ 2024-01-26 528/week @ 2024-02-02 3141/week @ 2024-02-09 2089/week @ 2024-02-16 1047/week @ 2024-02-23 1160/week @ 2024-03-01 1804/week @ 2024-03-08 1431/week @ 2024-03-15 1377/week @ 2024-03-22 1115/week @ 2024-03-29 1235/week @ 2024-04-05 2457/week @ 2024-04-12 2527/week @ 2024-04-19

7,533 downloads per month
Used in 9 crates (3 directly)

MIT license

27KB
732 lines

simplerand

Latest Version Minimum rustc version

Simple and fast random number generator

Motivation

I've worked on a fake data generator, which strongly relies on random number generation. The package, which serves this purpose in the world of Rust was the rand package. That's a cool package, if you want to have enterprise-level random generation. But for a simple fake data generator it's huge. Whatsoever, it takes 400+ microsec to generate a random number. (struggle)

So I`ve created a much simpler pseudo-random generator based on a very simple seeding mechanism. That won't serve cryptographic random generations! So it's only useful for projects like a fake data generator where a simple and fast solution is needed. Thid way I can generate random numbers in ~200 nanosec.

The random number generation is strongly based on the linear congruential generators, so if you are familiar with the algorithm you can imagine how simple it is.

Usage

extern crate simplerand;

use simplerand::{randn, rand_range};

fn main() {
    let data = randn(10000);
    println!("data: {}", data); // output: something between 0 and 10000

    let data = rand_range(3000, 10000);
    println!("data: {}", data); // output: something between 3000 and 10000

    let generic_data = rand_range::<f32>(1000.123, 30000.123)
    println!("data: {}", generic_data);
}
Use Randomable
extern crate simplerand;

use simplerand::{Randomable, rand_range};

fn main() {
    let generic_data = get_random_in_range::<u32>(10, 33);
    println!("data: {}", generic_data);
}

fn get_random_in_range<T: Randomable>(min: T, max: T) -> T {
    rand_range::<T>(min, max)
}
Singleton implementation
#[macro_use]
extern crate lazy_static;
extern crate simplerand;

use std::sync::Mutex;

lazy_static! {
    static ref rand: Mutex<simplerand::Rng> = Mutex::new(simplerand::Rng::new());
}

fn main() {
    let number = RNG.lock().unwrap().rand_range(0, 10000); // output: something between 0 and 10000
}

rand package

Since it took 400 microsec to generate a random number I thought it's because of the seeding mechanism. I wanted to setup the rand's ThreadRng as a static singleton variable on top of my declaration. I also used lazy_static to achive it, but it's not designed for that purpose, so I couldn't make it happen. (If someone has a solution for that I'm curious to see.)

Dependencies

~11KB