### Probability Distribution Sampling Example Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-weighted.md Samples from a set of categories with specified probabilities, demonstrating how `WeightedIndex` can be used to approximate a target probability distribution. This example uses floating-point weights. ```rust use rand::distr::weighted::WeightedIndex; // Categories: very rare, rare, common, very common // Probabilities: 1%, 9%, 40%, 50% let probs = [1.0, 9.0, 40.0, 50.0]; let dist = WeightedIndex::new(&probs).unwrap(); let categories = ["very rare", "rare", "common", "very common"]; let samples: Vec<_> = (0..1000) .map(|_| categories[dist.sample(&mut rng)]) .collect(); // `samples` now contains ~1% "very rare", ~50% "very common", etc. ``` -------------------------------- ### Bernoulli Distribution Construction and Sampling Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-distributions.md Shows how to create a `Bernoulli` distribution with a specified probability `p` of returning `true`. It includes an example of sampling from the distribution and notes the potential `InvalidProbability` error. ```rust use rand::distr::{Bernoulli, Distribution}; let dist = Bernoulli::new(0.3).unwrap(); let mut rng = rand::rng(); let value = dist.sample(&mut rng); // true 30% of time ``` -------------------------------- ### Custom Weight Implementation Example Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-weighted.md Demonstrates how to implement the `Weight` trait for a custom type. This example uses a `u32` wrapper and provides a `checked_add_assign` implementation that uses `checked_add` to prevent overflow. ```rust use rand::distr::weighted::Weight; #[derive(Clone, Copy)] struct MyWeight(u32); impl Weight for MyWeight { const ZERO: Self = MyWeight(0); fn checked_add_assign(&mut self, v: &Self) -> Result<(), ()> { self.0 = self.0.checked_add(v.0).ok_or(())?; Ok(()) } } ``` -------------------------------- ### Loot Table Example for Game Development Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-weighted.md Generates a random loot drop based on predefined weights for different item rarities. This example demonstrates using `WeightedIndex` to simulate a game's loot table. ```rust use rand::distr::weighted::WeightedIndex; #[derive(Debug, Clone)] enum Loot { Common { name: &'static str, weight: u32 }, Uncommon { name: &'static str, weight: u32 }, Rare { name: &'static str, weight: u32 }, Epic { name: &'static str, weight: u32 }, } let loot_table = vec![ ("iron sword", 100), ("steel armor", 80), ("gold ring", 40), ("legendary weapon", 5), ]; let weights: Vec = loot_table.iter().map(|(_, w)| *w).collect(); let dist = WeightedIndex::new(&weights).unwrap(); let mut rng = rand::rng(); let drop = &loot_table[dist.sample(&mut rng)]; println!("Dropped: {}", drop.0); ``` -------------------------------- ### Uniform Distribution Construction Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-distributions.md Provides examples of constructing `Uniform` distributions for half-open ranges `[low, high)` for both integer and floating-point types. It also notes the potential `InvalidRange` error. ```rust use rand::distr::Uniform; let dist = Uniform::new(0i32, 100).unwrap(); // [0, 100) let dist = Uniform::new(-1.0, 1.0).unwrap(); // [-1.0, 1.0) ``` -------------------------------- ### Uniform Inclusive Distribution Construction Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-distributions.md Demonstrates creating a `Uniform` distribution for a closed range `[low, high]`, suitable for discrete values like dice rolls. This example shows the construction and a subsequent sampling. ```rust let die = Uniform::new_inclusive(1, 6).unwrap(); // [1, 6] let mut rng = rand::rng(); let roll = rng.sample(die); ``` -------------------------------- ### Try-Catch with match for Bernoulli Distribution Source: https://github.com/rust-random/rand/blob/master/_autodocs/errors.md An example of using `match` to handle potential errors when creating a `Bernoulli` distribution. This pattern is useful when the input probability might be invalid. ```rust use rand::distr::{Bernoulli, Distribution}; match Bernoulli::new(0.3) { Ok(dist) => { let value = dist.sample(&mut rng); println!("{}", value); } Err(e) => eprintln!("Error: {}", e), } ``` -------------------------------- ### Creating Weighted Index Distribution with Invalid Weights Source: https://github.com/rust-random/rand/blob/master/_autodocs/errors.md Shows examples of creating a WeightedIndex distribution with invalid weights, such as negative, non-finite, or too large values, leading to an InvalidWeight error. ```rust let _ = WeightedIndex::new(&[-1, 5, 3]).unwrap(); // Error::InvalidWeight let _ = WeightedIndex::new(&[f64::INFINITY]).unwrap(); // Error::InvalidWeight ``` -------------------------------- ### Biased Coin Flip Example Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-weighted.md Simulates a biased coin flip with 70% probability for 'heads' and 30% for 'tails' using `WeightedIndex`. This snippet shows a practical application for simple probabilistic outcomes. ```rust use rand::distr::weighted::WeightedIndex; use rand::Distribution; // 70% heads, 30% tails let outcomes = ["heads", "tails"]; let weights = [70, 30]; let dist = WeightedIndex::new(&weights).unwrap(); let mut rng = rand::rng(); for _ in 0..100 { let outcome = outcomes[dist.sample(&mut rng)]; println!("{}", outcome); } ``` -------------------------------- ### Sample Method Usage Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-distributions.md Demonstrates how to use the `sample` method of a `Distribution` to generate a single random value. Requires importing `Distribution` and the specific distribution type. ```rust use rand::distr::{Distribution, Uniform}; let mut rng = rand::rng(); let die = Uniform::new_inclusive(1, 6).unwrap(); let roll = die.sample(&mut rng); // Or: rng.sample(die) ``` -------------------------------- ### Generate Docs with All Features Source: https://github.com/rust-random/rand/blob/master/_autodocs/configuration.md Build documentation using RUSTDOCFLAGS to enable all features, ensuring comprehensive API documentation is generated for all possible configurations. ```bash RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc --all-features ``` -------------------------------- ### Get Thread-Local RNG Source: https://github.com/rust-random/rand/blob/master/_autodocs/overview.md Retrieves the thread-local random number generator. This is a convenience function provided by the `thread_rng` feature. ```Rust use rand::Rng; let mut rng = rand::thread_rng(); let n: u32 = rng.gen(); println!("A random number: {}", n); ``` -------------------------------- ### Using SysRng and Seeding StdRng Source: https://github.com/rust-random/rand/blob/master/_autodocs/errors.md Demonstrates direct usage of SysRng for generating random u32 values and handling potential entropy errors. Also shows how to seed a StdRng from SysRng, with error handling for seeding failures. ```rust use rand::rngs::SysRng; use rand::{Rng, SeedableRng, rngs::StdRng}; // Using SysRng directly let mut sys = SysRng; match sys.try_next_u32() { Ok(value) => println!("{}", value), Err(getrandom_err) => eprintln!("Entropy error: {}", getrandom_err), } // Seeding from SysRng match StdRng::try_from_rng(&mut SysRng) { Ok(rng) => { /* use rng */ }, Err(e) => eprintln!("Could not seed from OS: {}", e), } ``` -------------------------------- ### Get Thread-Local RNG Handle Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-rngs.md Obtains a handle to the thread-local random number generator using the `rand::rng()` function. This RNG is automatically seeded and reseeded. ```rust use rand::rngs::ThreadRng; // Get thread-local RNG handle let mut rng = rand::rng(); ``` -------------------------------- ### Sample Bernoulli Distribution Directly and via RngExt Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-distributions.md Demonstrates sampling from a Bernoulli distribution directly using `sample` and indirectly using `RngExt` methods like `random_bool` and `random_ratio`. ```Rust use rand::distr::Bernoulli; let mut rng = rand::rng(); // Direct distribution let flip = Bernoulli::new(0.5).unwrap(); for _ in 0..10 { println!("{}", rng.sample(flip)); } // Via RngExt methods if rng.random_bool(0.5) { println!("heads"); } if rng.random_ratio(1, 2) { println!("tails"); } ``` -------------------------------- ### Sample Alphabetic Characters and Generate Strings Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-distributions.md Samples single ASCII letters (a-z, A-Z) as `u8` values and shows how to collect them into a `String`. ```Rust use rand::distr::Alphabetic; let letter: u8 = Alphabetic.sample(&mut rng); let word: String = Alphabetic .sample_iter(&mut rng) .take(10) .map(char::from) .collect(); ``` -------------------------------- ### Using SysRng for OS Entropy Source: https://github.com/rust-random/rand/blob/master/_autodocs/configuration.md Demonstrates using SysRng, which utilizes the operating system's entropy source for cryptographic seeding. Requires the 'sys_rng' feature. ```rust use rand::rngs::SysRng; use rand::{SeedableRng, rngs::StdRng, Rng}; let mut sys = SysRng; let x = sys.next_u64(); // From OS entropy let std_rng = StdRng::try_from_rng(&mut SysRng).unwrap(); ``` -------------------------------- ### Sample Iterator Usage Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-distributions.md Shows how to create an iterator using `sample_iter` to generate multiple random values from a distribution. The iterator can be collected into a Vec or used with other iterator methods. ```rust let die = Uniform::new_inclusive(1, 6).unwrap(); let rolls: Vec = die.sample_iter(&mut rng).take(100).collect(); ``` -------------------------------- ### Creating Uniform Distribution with Non-Finite Bounds Source: https://github.com/rust-random/rand/blob/master/_autodocs/errors.md Shows how attempting to create a Uniform distribution with non-finite bounds (NaN or Infinity) for floating-point types raises a NonFinite error. ```rust use rand::distr::Uniform; let _ = Uniform::new(0.0, f64::NAN).unwrap(); // Error::NonFinite let _ = Uniform::new(f32::NEG_INFINITY, 0.0).unwrap(); // Error::NonFinite ``` -------------------------------- ### Using ChaCha20Rng with a Seed Source: https://github.com/rust-random/rand/blob/master/_autodocs/configuration.md Demonstrates creating a ChaCha20Rng instance seeded with a specific value. Requires the 'chacha' feature. ```rust use rand::rngs::ChaCha20Rng; use rand::{SeedableRng, Rng}; let mut rng = ChaCha20Rng::seed_from_u64(0); ``` -------------------------------- ### Direct Entropy Sampling with SysRng Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-rngs.md Directly samples entropy from the operating system using `SysRng`. This is slower than other generators but provides secure entropy. ```rust use rand::{SeedableRng, Rng, rngs::{SysRng, StdRng}}; // Direct entropy sampling let mut rng = SysRng; let random_u64 = rng.next_u64().unwrap(); ``` -------------------------------- ### Embedded + SIMD Build Source: https://github.com/rust-random/rand/blob/master/_autodocs/configuration.md Enable 'alloc' and 'simd_support' features for embedded systems requiring SIMD acceleration. This configuration requires Nightly Rust and the portable_simd feature. ```toml [dependencies] rand = { version = "0.10", default-features = false, features = ["alloc", "simd_support"] } ``` -------------------------------- ### no_std with Allocator Support Source: https://github.com/rust-random/rand/blob/master/_autodocs/configuration.md Enable the 'alloc' feature for no_std environments to add support for sequence operations, weighted sampling, and iterator collection. ```toml [dependencies] rand = { version = "0.10", default-features = false, features = ["alloc"] } ``` -------------------------------- ### Expect for Bernoulli Distribution Source: https://github.com/rust-random/rand/blob/master/_autodocs/errors.md Shows how to use `expect` when creating a `Bernoulli` distribution, providing a custom panic message if the probability is invalid. This is preferred over `unwrap` for better error reporting. ```rust let dist = Bernoulli::new(p) .expect("probability must be between 0 and 1"); ``` -------------------------------- ### Unwrap for Bernoulli Distribution Source: https://github.com/rust-random/rand/blob/master/_autodocs/errors.md Demonstrates using `unwrap` to create a `Bernoulli` distribution. This should only be used when the input probability is guaranteed to be valid, as it will panic on error. ```rust // Only use when you're certain the input is valid let dist = Bernoulli::new(0.5).unwrap(); let value = dist.sample(&mut rng); ``` -------------------------------- ### Weighted Choices (Pattern) Source: https://github.com/rust-random/rand/blob/master/_autodocs/guide.md Shows how to make weighted random choices from a list of items. It uses `WeightedIndex` to define probabilities for each item and then samples an index to select the corresponding choice. ```rust use rand::distr::weighted::WeightedIndex; let choices = ["common", "uncommon", "rare"]; let weights = [70, 25, 5]; // Percentages let dist = WeightedIndex::new(&weights).unwrap(); let mut rng = rand::rng(); let choice = choices[rng.sample(dist)]; ``` -------------------------------- ### Create Bernoulli Distribution from Ratio Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-distributions.md Constructs a Bernoulli distribution using a numerator and denominator to define the probability. Ensure the numerator is less than or equal to the denominator, and the denominator is greater than zero. ```Rust let dist = Bernoulli::from_ratio(1, 6).unwrap(); // 1/6 probability let flip = dist.sample(&mut rng); ``` -------------------------------- ### SIMD Support Feature Selection (Nightly Only) Source: https://github.com/rust-random/rand/blob/master/_autodocs/configuration.md Enables experimental SIMD support for high-performance vector sampling. Requires nightly Rust. ```toml rand = { version = "0.10", features = ["simd_support"] } ``` -------------------------------- ### StandardUniform Construction and Usage Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-distributions.md Shows how to construct and use the `StandardUniform` distribution directly or via the `RngExt::random()` method for type inference. ```rust use rand::distr::StandardUniform; let mut rng = rand::rng(); let x = StandardUniform.sample(&mut rng); // Type inferred context // Or via RngExt::random() let y: u32 = rng.random(); ``` -------------------------------- ### Sample from Half-Open Interval (0, 1] Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-distributions.md Samples floating-point numbers from a uniform distribution in the interval (0, 1], which includes 1 but excludes 0. ```Rust use rand::distr::OpenClosed01; let x: f32 = OpenClosed01.sample(&mut rng); // x in (0.0, 1.0] let y: f64 = OpenClosed01.sample(&mut rng); // y in (0.0, 1.0] ``` -------------------------------- ### Creating Uniform Distribution with Empty Range Source: https://github.com/rust-random/rand/blob/master/_autodocs/errors.md Illustrates creating a Uniform distribution where the lower bound is greater than or equal to the upper bound, resulting in an EmptyRange error for non-inclusive ranges. ```rust let _ = Uniform::new(100u32, 50).unwrap(); // Error::EmptyRange let _ = Uniform::new(-10.5, -20.3).unwrap(); // Error::EmptyRange ``` -------------------------------- ### Repeating Samples from Fixed Range (Pattern) Source: https://github.com/rust-random/rand/blob/master/_autodocs/guide.md Demonstrates an optimized pattern for repeatedly sampling from a fixed range by constructing a `Uniform` distribution once. This is more efficient than calling `random_range` in a loop. ```rust use rand::distr::Uniform; let range = Uniform::new(1, 100).unwrap(); let mut rng = rand::rng(); for _ in 0..1000 { let value = rng.sample(range); } ``` -------------------------------- ### Optimize WeightedIndex Sampling by Reusing Distribution Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-weighted.md Illustrates the performance benefit of creating a WeightedIndex distribution once and reusing it for multiple samples, rather than recreating it repeatedly. ```rust // Good - distribute created once let dist = WeightedIndex::new(&weights).unwrap(); for _ in 0..1000 { let idx = dist.sample(&mut rng); } // Slower - recreates distribution for _ in 0..1000 { let idx = WeightedIndex::new(&weights).unwrap().sample(&mut rng); } ``` -------------------------------- ### Sampling Multiple Values (Pattern) Source: https://github.com/rust-random/rand/blob/master/_autodocs/guide.md Demonstrates various methods for sampling multiple random values. This includes creating an iterator of random values, filling a slice directly, and filling a pre-allocated buffer. ```rust // Iterator let values: Vec = rng.random_iter().take(100).collect(); // Slice let arr: [u32; 100] = rng.random(); // Fill let mut buf = vec![0u32; 100]; rng.fill(&mut buf); ``` -------------------------------- ### Sample from Open Interval (0, 1) Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-distributions.md Samples floating-point numbers from a uniform distribution strictly between 0 and 1 (exclusive of both endpoints). ```Rust use rand::distr::Open01; let x: f32 = Open01.sample(&mut rng); // x in (0.0, 1.0) let y: f64 = Open01.sample(&mut rng); // y in (0.0, 1.0) ``` -------------------------------- ### Enabling SIMD Support (Nightly) Source: https://github.com/rust-random/rand/blob/master/_autodocs/configuration.md A placeholder indicating that the 'simd_support' feature is enabled, which requires nightly Rust and enables SIMD vector sampling. ```rust #![feature(portable_simd)] // Enables sampling of SIMD types ``` -------------------------------- ### Minimal no_std Configuration Source: https://github.com/rust-random/rand/blob/master/_autodocs/configuration.md Configure Rand for a minimal no_std environment by disabling default features. This includes core traits, StandardUniform, SmallRng, and Xoshiro generators, but excludes thread-local and OS entropy. ```toml [dependencies] rand = { version = "0.10", default-features = false } ``` -------------------------------- ### Creating Weighted Index Distribution with Insufficient Non-Zero Weights Source: https://github.com/rust-random/rand/blob/master/_autodocs/errors.md Illustrates the InsufficientNonZero error, which occurs when there are not enough non-zero weights for the sampling requirements, such as all weights being zero. ```rust let _ = WeightedIndex::new(&[0u32, 0, 0]).unwrap(); // Error::InsufficientNonZero ``` -------------------------------- ### SysRng Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-rngs.md SysRng provides a stateless interface to the operating system's entropy source. It is suitable for seeding other generators or for security-critical single samples. ```APIDOC ## SysRng ### Description Stateless interface to the operating system's entropy source. Suitable for seeding other generators or for security-critical single samples. ### Properties - Security: Secure entropy from OS - Speed: Slower than other generators; direct OS calls - State: Stateless; each call queries OS - Availability: Via `getrandom` crate; limited WebAssembly support ### Struct Definition ```rust pub struct SysRng; ``` ### Usage ```rust use rand::{SeedableRng, Rng, rngs::{SysRng, StdRng}}; // Direct entropy sampling let mut rng = SysRng; let random_u64 = rng.next_u64().unwrap(); // Seeding another generator let mut std_rng = StdRng::try_from_rng(&mut SysRng).unwrap(); ``` ### Traits Implemented - `TryRng` - `TryCryptoRng` - `SeedableRng` - `Clone` ### Error Type `getrandom::Error` - See getrandom crate documentation. ``` -------------------------------- ### Implementing a Custom Distribution Source: https://github.com/rust-random/rand/blob/master/_autodocs/guide.md You can implement the `Distribution` trait to create your own custom random number distributions. The `sample` method defines the logic for generating random values. ```rust use rand::distr::Distribution; use rand::Rng; struct CustomDist; impl Distribution for CustomDist { fn sample(&self, rng: &mut R) -> f64 { // Custom sampling logic rng.random::() * 2.0 - 1.0 // Range [-1, 1) } } let custom = CustomDist; let value = custom.sample(&mut rng); ``` -------------------------------- ### Sample Elements from Slice Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-sequences.md Demonstrates sampling elements from a slice. Requires the `IndexedRandom` trait. ```rust use rand::seq::IndexedRandom; let slice = &[10, 20, 30, 40, 50]; let samples = slice.choose_samples(&mut rng, 3); for sample in samples { println!("{}", sample); } ``` -------------------------------- ### Sample Alphanumeric Characters and Generate Strings Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-distributions.md Samples single alphanumeric characters (a-z, A-Z, 0-9) as `u8` values and demonstrates collecting these samples into a `String` for generating random passwords or tokens. ```Rust use rand::distr::{Alphanumeric, Distribution}; let mut rng = rand::rng(); // Single character let c: u8 = Alphanumeric.sample(&mut rng); // String let password: String = Alphanumeric .sample_iter(&mut rng) .take(16) .map(char::from) .collect(); ``` -------------------------------- ### WebAssembly without Getrandom Source: https://github.com/rust-random/rand/blob/master/_autodocs/configuration.md Configure Rand for WebAssembly by disabling default features and explicitly enabling 'std' and 'std_rng'. This approach avoids reliance on 'getrandom' for entropy. ```toml [dependencies] rand = { version = "0.10", default-features = false, features = ["std", "std_rng"] } ``` -------------------------------- ### Implement Distribution Trait Source: https://github.com/rust-random/rand/blob/master/_autodocs/overview.md Shows how to implement the `Distribution` trait for custom probability distributions. This allows users to generate random values according to their own defined distributions. ```Rust use rand::distributions::{Distribution, Uniform}; use rand::Rng; struct MyDistribution; impl Distribution for MyDistribution { fn sample(&self, rng: &mut R) -> f64 { // Example: Sample from a uniform distribution between 0 and 1 Uniform::new(0.0, 1.0).sample(rng) } } let mut rng = rand::thread_rng(); let sample: f64 = MyDistribution.sample(&mut rng); println!("Sample from custom distribution: {}", sample); ``` -------------------------------- ### Use Uniform Distribution Source: https://github.com/rust-random/rand/blob/master/_autodocs/overview.md Demonstrates the use of the `Uniform` distribution for sampling random values within a specified range. This is a common and fundamental distribution. ```Rust use rand::distributions::{Distribution, Uniform}; use rand::Rng; let mut rng = rand::thread_rng(); let die_roll = Uniform::new_inclusive(1, 6); let value = die_roll.sample(&mut rng); println!("Rolled a die: {}", value); ``` -------------------------------- ### Using RngReader to Read Random Data Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-rngs.md Shows how to use the RngReader adapter to read random bytes into a buffer from a system random number generator (SysRng). ```rust use rand::RngReader; use std::io::Read; use std::fs::File; let mut rng = rand::rngs::SysRng; let mut reader = RngReader(rng); let mut buf = vec![0u8; 1024]; reader.read_exact(&mut buf).unwrap(); ``` -------------------------------- ### Generate Random Boolean with Rational Probability using RngExt Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-rngext.md Use `random_ratio(numerator, denominator)` to return `true` with a probability of `numerator/denominator`. This provides a cleaner syntax for rational probabilities compared to `random_bool()`. It panics if the denominator is zero or the numerator exceeds the denominator. ```rust use rand::RngExt; let mut rng = rand::rng(); if rng.random_ratio(2, 3) { println!("About 67% chance!"); } if rng.random_ratio(1, 6) { println!("About 17% chance!"); } ``` -------------------------------- ### Compare Uniform and WeightedIndex for Custom Probabilities Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-weighted.md Contrasts Uniform sampling (equal probability) with WeightedIndex (custom probability per outcome), illustrating how to achieve weighted selection from a list. ```rust // Uniform - each outcome equally likely let choice = rng.random_range(0..items.len()); // WeightedIndex - weighted selection let choice = dist.sample(&mut rng); ``` -------------------------------- ### Creating Bernoulli Distribution with Invalid Probability Source: https://github.com/rust-random/rand/blob/master/_autodocs/errors.md Demonstrates how creating a Bernoulli distribution with probabilities outside the valid [0.0, 1.0] range results in an InvalidProbability error. This can be handled via `unwrap()` panics or `match` statements. ```rust use rand::distr::Bernoulli; // Panics via unwrap let _ = Bernoulli::new(-0.5).unwrap(); // InvalidProbability let _ = Bernoulli::new(1.5).unwrap(); // InvalidProbability let _ = Bernoulli::from_ratio(10, 5).unwrap(); // InvalidProbability // Or handle gracefully match Bernoulli::new(0.3) { Ok(dist) => { /* use distribution */ }, Err(BernoulliError::InvalidProbability) => eprintln!("Invalid probability") } ``` -------------------------------- ### Creating Weighted Index Distribution with Empty Input Source: https://github.com/rust-random/rand/blob/master/_autodocs/errors.md Demonstrates that providing an empty slice of weights to WeightedIndex::new results in an InvalidInput error. ```rust use rand::distr::weighted::WeightedIndex; let _ = WeightedIndex::new(&[]).unwrap(); // Error::InvalidInput ``` -------------------------------- ### Minimal (no_std with alloc) Feature Selection Source: https://github.com/rust-random/rand/blob/master/_autodocs/configuration.md Configures the rand crate for minimal, no_std environments that still require heap allocation support. ```toml rand = { version = "0.10", default-features = false, features = ["alloc"] } ``` -------------------------------- ### Seeding StdRng with a Value Source: https://github.com/rust-random/rand/blob/master/_autodocs/configuration.md Shows how to create a deterministic StdRng by seeding it with a specific u64 value. Requires the 'std_rng' feature. ```rust use rand::rngs::StdRng; use rand::{SeedableRng, Rng}; let mut rng = StdRng::seed_from_u64(12345); let x = rng.next_u32(); ``` -------------------------------- ### Enable Getrandom for Wasm Source: https://github.com/rust-random/rand/blob/master/_autodocs/configuration.md Configure Rand for WebAssembly by enabling the 'js' feature for the 'getrandom' crate. This ensures proper entropy collection in Wasm environments. ```toml [dependencies] getrandom = { version = "0.4", features = ["js"] } rand = { version = "0.10", features = ["sys_rng"] } ``` -------------------------------- ### Compare Bernoulli and WeightedIndex for Binary Choices Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-weighted.md Differentiates between Bernoulli (two outcomes, explicit probability) and WeightedIndex (multiple outcomes with weights), showing their respective use cases for binary selections. ```rust // Bernoulli - simple probability let flip = Bernoulli::new(0.3).unwrap().sample(&mut rng); // true or false // WeightedIndex - multiple weighted choices let choice = WeightedIndex::new(&[30, 70]).unwrap().sample(&mut rng); // 0 or 1 ``` -------------------------------- ### Sample from Iterator Source: https://github.com/rust-random/rand/blob/master/_autodocs/overview.md Provides methods for sampling elements from iterators. This includes choosing a single random element or multiple elements. ```Rust use rand::seq::IteratorRandom; use rand::Rng; let data = vec![10, 20, 30, 40, 50]; let mut rng = rand::thread_rng(); // Sample a single element let sample = data.iter().choose(&mut rng); println!("Randomly chosen element: {:?}", sample); // Sample multiple elements (without replacement) let samples = data.iter().choose_multiple(&mut rng, 3); println!("Three randomly chosen elements: {:?}", samples); ``` -------------------------------- ### Adding Rand Crate Dependency Source: https://github.com/rust-random/rand/blob/master/_autodocs/guide.md To use the 'rand' crate, add it to your `Cargo.toml` file under the `[dependencies]` section. Specify the desired version. ```toml [dependencies] rand = "0.10" ``` -------------------------------- ### Open01 Struct Source: https://github.com/rust-random/rand/blob/master/_autodocs/types.md Open01 is a distribution that samples floating-point numbers from the open interval (0, 1). ```APIDOC ## Open01 Struct ### Description Distribution sampling floats from `(0, 1)`. ### Implements `Distribution`, `Distribution` ``` -------------------------------- ### Sample a value from a distribution Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-rngext.md Use this method to draw a single random value from a specified distribution. It supports various distribution types like Uniform and Bernoulli. Reusing a distribution object can be more efficient for multiple samples. ```rust use rand::RngExt; use rand::distr::{Uniform, Bernoulli}; let mut rng = rand::rng(); // Uniform distribution let die = Uniform::new_inclusive(1, 6).unwrap(); let roll: u32 = rng.sample(die); // Bernoulli distribution let coin = Bernoulli::new(0.5).unwrap(); let heads: bool = rng.sample(coin); // Reusing distribution is faster than multiple samples for _ in 0..1000 { let _roll = rng.sample(die); } ``` -------------------------------- ### Using Thread-Local RNG Convenience Functions Source: https://github.com/rust-random/rand/blob/master/_autodocs/configuration.md Illustrates the use of top-level convenience functions like rand::random() and rand::rng() provided by the 'thread_rng' feature. ```rust // Only works with "thread_rng" let x: u32 = rand::random(); let r = rand::rng(); ``` -------------------------------- ### No-std Only Feature Selection Source: https://github.com/rust-random/rand/blob/master/_autodocs/configuration.md Configures the rand crate for environments that do not use the standard library and do not require heap allocation. ```toml rand = { version = "0.10", default-features = false } ``` -------------------------------- ### Uniform Empty Range Fallback Source: https://github.com/rust-random/rand/blob/master/_autodocs/errors.md Demonstrates a strategy for handling empty ranges when creating a `Uniform` distribution. It checks if `low < high` before attempting to create the distribution, returning `None` if the range is invalid. ```rust let dist = if low < high { Uniform::new(low, high).ok() } else { None }; ``` -------------------------------- ### Use a Reusable Uniform Distribution for Sampling Source: https://github.com/rust-random/rand/blob/master/_autodocs/guide.md Creates a reusable `Uniform` distribution for sampling integers within a specific inclusive range. This is more performant for repeated sampling compared to `random_range`. ```rust use rand::distr::Uniform; let die = Uniform::new_inclusive(1, 6).unwrap(); let mut rng = rand::rng(); for _ in 0..100 { let roll = rng.sample(die); println!("{}", roll); } ``` -------------------------------- ### Reuse Distributions for Efficient Sampling Source: https://github.com/rust-random/rand/blob/master/_autodocs/configuration.md Create distribution objects like Uniform once and reuse them for multiple sampling operations. This is more efficient than recreating the distribution for each sample. ```rust use rand::distr::Uniform; let dist = Uniform::new(0, 100).unwrap(); for _ in 0..1000 { let val = rng.sample(dist); // Efficient } ``` -------------------------------- ### Bernoulli::from_ratio Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-distributions.md Creates a Bernoulli distribution using a numerator and denominator to define the probability. It returns a Result which can be Ok or Err if the probability is invalid. ```APIDOC ## Bernoulli::from_ratio(numerator, denominator) ### Description Creates a Bernoulli distribution with rational probability. ### Method Rust function call ### Parameters #### Path Parameters - **numerator** (u32) - Required - Numerator of probability (≤ denominator) - **denominator** (u32) - Required - Denominator of probability (> 0) ### Request Example ```rust let dist = Bernoulli::from_ratio(1, 6).unwrap(); // 1/6 probability let flip = dist.sample(&mut rng); ``` ### Response #### Success Response - `Self` (Bernoulli distribution) #### Error Response - `BernoulliError` (e.g., `InvalidProbability` if conditions not met) ``` -------------------------------- ### Using the Fill Trait to Fill a Slice Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-rngs.md Demonstrates how to use the Fill trait to efficiently fill a slice of u32 values with random data using a thread-local RNG. ```rust use rand::RngExt; let mut rng = rand::rng(); let mut buffer = [0u32; 128]; rng.fill(&mut buffer); // Fill with random data ``` -------------------------------- ### One-time Range Sampling (Pattern) Source: https://github.com/rust-random/rand/blob/master/_autodocs/guide.md Illustrates the pattern for single random number generation within a range using `random_range`. This method is optimized for one-off sampling and avoids the overhead of creating a distribution object. ```rust let value: i32 = rng.random_range(1..100); ``` -------------------------------- ### Optimize WeightedIndex by Updating Weights In-Place Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-weighted.md Shows the efficiency of updating existing weights of a WeightedIndex distribution compared to creating a new distribution with the updated weights. ```rust // Good - updates in place dist.update_weights(&new_weights).unwrap(); // Slower - recreates let dist = WeightedIndex::new(&new_weights).unwrap(); ``` -------------------------------- ### Construct SmallRng from Fixed Seed Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-rngs.md Constructs a SmallRng using a fixed 64-bit seed. This method provides deterministic output. ```rust use rand::{SeedableRng, rngs::SmallRng}; // From fixed seed let mut rng = SmallRng::seed_from_u64(12345); ``` -------------------------------- ### RngExt::random_ratio Panic Conditions Source: https://github.com/rust-random/rand/blob/master/_autodocs/errors.md Demonstrates panic conditions for `random_ratio`: division by zero when the denominator is 0, and sampling an invalid ratio when the numerator is greater than the denominator. ```rust let _ = rng.random_ratio(1, 0); // Panics: division by zero let _ = rng.random_ratio(10, 5); // Panics: invalid ratio ``` -------------------------------- ### SysRng Source: https://github.com/rust-random/rand/blob/master/_autodocs/types.md SysRng is an operating system entropy source for generating random numbers. It re-exports from the getrandom crate. ```APIDOC ## SysRng ### Description Operating system entropy source. ### Source `rand::rngs::SysRng` (re-export from `getrandom`) ### Implements `TryRng`, `TryCryptoRng`, `SeedableRng`, `Clone` ``` -------------------------------- ### Prelude Re-exports Source: https://github.com/rust-random/rand/blob/master/_autodocs/types.md The `rand::prelude` module re-exports commonly used items for convenience, including core traits like Rng and Distribution, and popular RNG types. ```APIDOC ## Prelude Re-exports ### Description The `rand::prelude` module re-exports commonly used items. ### Re-exports - `crate::distr::Distribution` - `crate::rngs::SmallRng` - `crate::rngs::StdRng` (std_rng feature) - `crate::rngs::ThreadRng` (thread_rng feature) - `crate::seq::{IndexedMutRandom, IndexedRandom, IteratorRandom, SliceRandom}` - `crate::{CryptoRng, Rng, RngExt, SeedableRng}` ``` -------------------------------- ### Integrating Rand with Rayon for Parallel Computation Source: https://github.com/rust-random/rand/blob/master/_autodocs/guide.md To use `rand` with Rayon for parallel computations, add both crates to your `Cargo.toml`. Each parallel task can create its own `SmallRng` instance. ```toml [dependencies] rand = "0.10" rayon = "1.7" ``` ```rust use rayon::prelude::*; use rand::rngs::SmallRng; use rand::{SeedableRng, Rng}; let results: Vec<_> = (0..1000) .into_par_iter() .map(|_| { let mut rng = SmallRng::from_entropy(); rng.next_u32() }) .collect(); ``` -------------------------------- ### Reproducibility with Distributions Source: https://github.com/rust-random/rand/blob/master/_autodocs/configuration.md Illustrates how enabling the 'unbiased' feature can alter the output of random number generation, even when using the same seed. This highlights the importance of feature selection for reproducibility. ```rust // With default features let v1 = rng.random_range(0..100); // With unbiased feature let v2 = rng.random_range(0..100); // Different value! ``` -------------------------------- ### Prelude Re-exports Source: https://github.com/rust-random/rand/blob/master/_autodocs/types.md Commonly used types and traits from the 'rand' crate re-exported in the `rand::prelude` module for convenience. ```rust pub use crate::distr::Distribution; pub use crate::rngs::SmallRng; pub use crate::rngs::StdRng; // std_rng feature pub use crate::rngs::ThreadRng; // thread_rng feature pub use crate::seq::{IndexedMutRandom, IndexedRandom, IteratorRandom, SliceRandom}; pub use crate::{CryptoRng, Rng, RngExt, SeedableRng}; ``` -------------------------------- ### Generic Function for Random Configuration (Pattern) Source: https://github.com/rust-random/rand/blob/master/_autodocs/guide.md Provides a pattern for a generic function that generates random data, such as a configuration object. It accepts any type implementing `Rng` and `?Sized`, making it versatile. ```rust use rand::{Rng, RngExt}; fn generate_config(rng: &mut R) -> Config { Config { id: rng.random(), name: format!("instance-{}", rng.random::()), enabled: rng.random_bool(0.8), } } // Works with any RNG let config = generate_config(&mut rand::rng()); ``` -------------------------------- ### SysRng Structure Source: https://github.com/rust-random/rand/blob/master/_autodocs/types.md Represents the operating system's entropy source for random number generation. ```rust pub struct SysRng; ``` -------------------------------- ### Sample from Infinite Iterator Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-sequences.md Selects a single random element from an infinite range iterator (1 to infinity). Requires importing `IteratorRandom`. ```rust use rand::seq::IteratorRandom; let sample = (1..).choose(&mut rng); // Uniform random from 1..∞ ``` -------------------------------- ### Fast Bulk Generation with SmallRng Source: https://github.com/rust-random/rand/blob/master/_autodocs/configuration.md Utilize SmallRng for significantly faster bulk random number generation compared to StdRng. Seed it with a value to ensure reproducible sequences. ```rust use rand::rngs::SmallRng; // 3-4x faster for bulk generation let mut rng = SmallRng::seed_from_u64(0); ``` -------------------------------- ### Custom Error Handling for Uniform Distribution Source: https://github.com/rust-random/rand/blob/master/_autodocs/errors.md Illustrates a custom error handling function for creating a `Uniform` distribution. It maps the distribution's potential error into a `String` error type for more specific error reporting. ```rust use rand::distr::Uniform; fn create_range(low: f64, high: f64) -> Result, String> { Uniform::new(low, high) .map_err(|_| format!("Invalid range: {} to {}", low, high)) } let dist = create_range(0.0, 1.0)?; ``` -------------------------------- ### Create WeightedIndex with Float Weights Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-weighted.md Samples from a distribution where weights are represented as floating-point numbers. The weights are normalized internally and do not need to sum to 1.0. ```rust use rand::distr::weighted::WeightedIndex; // Probabilities don't need to sum to 100 let weights = [0.1f64, 0.3, 0.6]; // Normalized internally let dist = WeightedIndex::new(&weights).unwrap(); for _ in 0..10 { println!("{}", dist.sample(&mut rng)); } ``` -------------------------------- ### Construct StdRng from Fixed Seed Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-rngs.md Constructs a StdRng using a fixed 64-bit seed. This method is deterministic and not suitable for security-sensitive applications. ```rust use rand::{SeedableRng, rngs::StdRng}; // From fixed seed (deterministic, not secure for crypto) let mut rng = StdRng::seed_from_u64(12345); ``` -------------------------------- ### Serialization Support Feature Selection Source: https://github.com/rust-random/rand/blob/master/_autodocs/configuration.md Enables the 'serde' feature for the rand crate, allowing for serialization of RNG states. ```toml rand = { version = "0.10", features = ["serde"] } ``` -------------------------------- ### Construct StdRng from OS Entropy Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-rngs.md Constructs a StdRng using entropy from the system's random number generator. This is the most secure method for cryptographic applications. ```rust use rand::{SeedableRng, rngs::StdRng}; // From OS entropy (most secure) let mut rng = StdRng::try_from_rng(&mut rand::rngs::SysRng).unwrap(); ``` -------------------------------- ### Enable Serde Support for RNGs Source: https://github.com/rust-random/rand/blob/master/_autodocs/configuration.md Use this snippet to enable serialization and deserialization support for specific RNG types like StdRng, SmallRng, and Xoshiro variants. Requires the 'serde' crate with the 'derive' feature. ```toml [dependencies] rand = { version = "0.10", features = ["serde"] } serde = { version = "1.0", features = ["derive"] } ``` -------------------------------- ### Construct SmallRng via Convenience Function Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-rngs.md Constructs a SmallRng using the convenience function `rand::make_rng()`. This RNG is auto-seeded from OS entropy. ```rust use rand::rngs::SmallRng; // Auto-seeded from OS entropy let mut rng: SmallRng = rand::make_rng(); ``` -------------------------------- ### Uniform Sampling Performance Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-distributions.md Highlights the performance benefit of reusing a constructed `Uniform` distribution for multiple samples compared to creating a new one each time. The `rng.sample(dist)` method is efficient for this. ```rust let dist = Uniform::new(1u32, 101).unwrap(); for _ in 0..1000 { let val = rng.sample(dist); // Efficient } ``` -------------------------------- ### Choose One Element from Slice Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-sequences.md Uniformly sample one element from an indexable collection. Returns `None` if the collection is empty. Time complexity is O(1) for slices. ```rust use rand::seq::IndexedRandom; let numbers = [1, 2, 4, 8, 16, 32]; let mut rng = rand::rng(); match numbers.choose(&mut rng) { Some(elem) => println!("Picked {}", elem), None => println!("Empty list"), } ``` -------------------------------- ### Implement StandardUniform for Custom Types Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-distributions.md Shows how to make a custom struct compatible with `rng.random::()` by implementing the `Distribution` trait for `StandardUniform`. ```Rust use rand::distr::{Distribution, StandardUniform}; struct MyType(f32); impl Distribution for StandardUniform { fn sample(&self, rng: &mut R) -> MyType { MyType(rng.random()) } } // Now works with rng.random::() let x: MyType = rng.random(); ``` -------------------------------- ### Iterate Samples with Replacement from Slice Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-sequences.md Provides an iterator for sampling elements with replacement from an indexable collection. Returns `None` if the collection is empty. The same element can be picked multiple times. ```rust let choices = ['a', 'b', 'c', 'd', 'e']; let mut rng = rand::rng(); if let Some(iter) = choices.choose_iter(&mut rng) { for choice in iter.take(5) { println!("{}", choice); } } ``` -------------------------------- ### WeightedIndex::new Constructor Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-weighted.md Creates a new WeightedIndex distribution from an iterator of weights. Supports integer and floating-point weights. Returns an error for invalid inputs like empty weights, negative weights, or all zero weights. ```rust fn new(weights: I) -> Result where I: IntoIterator, I::Item: SampleBorrow, ``` ```rust use rand::distr::weighted::WeightedIndex; use rand::Distribution; // Integer weights let dist = WeightedIndex::new(&[1u32, 2, 3, 4]).unwrap(); let item = dist.sample(&mut rng); // Returns 0, 1, 2, or 3 // Float weights let dist = WeightedIndex::new(&[0.5f64, 1.5, 2.0]).unwrap(); // Via iterator let weights = vec![10, 20, 30]; let dist = WeightedIndex::new(&weights).unwrap(); ``` -------------------------------- ### Conditional Distribution Selection Source: https://github.com/rust-random/rand/blob/master/_autodocs/configuration.md Enable weighted sampling distributions when the 'alloc' feature is available. This allows for efficient selection of items based on associated weights. ```rust #[cfg(feature = "alloc")] fn with_weighted_sampling() { use rand::distr::weighted::WeightedIndex; let dist = WeightedIndex::new(&[1, 2, 3]).unwrap(); } ``` -------------------------------- ### Handle Errors During WeightedIndex Creation Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-weighted.md Provides a robust way to create a WeightedIndex distribution by mapping potential errors to descriptive strings. This is crucial for validating input weights. ```rust use rand::distr::weighted::WeightedIndex; fn create_weighted_choice(weights: &[u32]) -> Result, String> { WeightedIndex::new(weights) .map_err(|e| match e { rand::distr::weighted::Error::InvalidInput => "Weight array must not be empty".to_string(), rand::distr::weighted::Error::InvalidWeight => "All weights must be non-negative".to_string(), rand::distr::weighted::Error::InsufficientNonZero => "At least one weight must be greater than zero".to_string(), rand::distr::weighted::Error::Overflow => "Weights sum to infinity or overflow".to_string(), }) } match create_weighted_choice(&[1, 2, 3]) { Ok(dist) => println!("Distribution created"), Err(e) => eprintln!("Error: {}", e), } ``` -------------------------------- ### Performance Benefit of Integer Weights in WeightedIndex Source: https://github.com/rust-random/rand/blob/master/_autodocs/api-weighted.md Highlights that using integer weights for WeightedIndex can be faster due to avoiding floating-point operations. ```rust // Faster WeightedIndex::new(&[1u32, 2, 3]).unwrap(); // Slower (float operations) WeightedIndex::new(&[1.0f64, 2.0, 3.0]).unwrap(); ``` -------------------------------- ### Use RNG as Iterator Source Source: https://github.com/rust-random/rand/blob/master/_autodocs/guide.md Shows how to use a random number generator as a source for creating random iterators. Requires the RngExt trait. ```rust use rand::RngExt; let mut rng = rand::rng(); let random_pairs: Vec<(u32, u32)> = rng .random_iter::() .zip(rng.random_iter::()) .take(10) .collect(); ``` -------------------------------- ### Share Thread-Safe RNG with Mutex Source: https://github.com/rust-random/rand/blob/master/_autodocs/guide.md Demonstrates how to share a random number generator across multiple threads using a Mutex. Ensure you import Mutex and StdRng. ```rust use std::sync::Mutex; use rand::rngs::StdRng; let shared_rng = Mutex::new(StdRng::from_entropy()); // In each thread let mut rng = shared_rng.lock().unwrap(); let value = rng.next_u32(); ```