### Exp1 Sample Generation Example Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/exponential-gamma.md A complete example showing how to generate a sample from the Exp1 distribution and print it. ```rust use rand_distr::Exp1; let mut rng = rand::rng(); let value: f64 = Exp1.sample(&mut rng); println!("Exponential(1) sample: {}", value); ``` -------------------------------- ### Exp Basic Sampling Example Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/exponential-gamma.md Demonstrates creating an Exp distribution with a rate of 0.5 and sampling a single value. ```rust use rand_distr::{Exp, Distribution}; let exp = Exp::new(0.5).unwrap(); let value = exp.sample(&mut rand::rng()); println!("Exponential(0.5) sample: {}", value); ``` -------------------------------- ### StandardNormal Example Usage Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/normal-distribution.md A complete example showing how to initialize a random number generator, sample a value from the StandardNormal distribution, and print the result. ```rust use rand::prelude::*; use rand_distr::StandardNormal; let mut rng = rand::rng(); let value: f64 = StandardNormal.sample(&mut rng); println!("Standard normal sample: {}", value); ``` -------------------------------- ### Example Usage of Triangular Distribution Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/other-continuous.md Demonstrates how to create and sample from a Triangular distribution with min=0.0, mode=5.0, and max=10.0. ```rust use rand_distr::{Triangular, Distribution}; // min=0, mode=5, max=10 let tri = Triangular::new(0.0, 5.0, 10.0).unwrap(); let value = tri.sample(&mut rand::rng()); println!("Triangular sample: {}", value); ``` -------------------------------- ### LogNormal Example: Log-space Construction Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/normal-distribution.md Demonstrates constructing a LogNormal distribution using log-space parameters and sampling a value. ```rust use rand_distr::{LogNormal, Distribution}; let log_normal = LogNormal::new(2.0, 3.0).unwrap(); let value = log_normal.sample(&mut rand::rng()); println!("{} is from log N(2, 9)", value); ``` -------------------------------- ### Exp Simulation Example Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/exponential-gamma.md Illustrates using the Exp distribution to simulate arrival times, with a mean of 5 seconds (λ = 0.2). ```rust use rand_distr::{Exp, Distribution}; use std::time::Duration; // Simulate arrival times (mean 5 seconds) let exp = Exp::new(0.2).unwrap(); // λ = 1/5 let mut rng = rand::rng(); for _ in 0..10 { let wait_time = exp.sample(&mut rng); println!("Wait: {:?}", Duration::from_secs_f64(wait_time)); } ``` -------------------------------- ### PERT Distribution Example Usage Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/other-continuous.md Demonstrates how to create and sample from a PERT distribution for project time estimation. Requires importing Pert and Distribution traits. ```rust use rand_distr::{Pert, Distribution}; let pert = Pert::new(1.0, 5.0, 10.0).unwrap(); let estimate = pert.sample(&mut rand::rng()); println!("Project time estimate: {}", estimate); ``` -------------------------------- ### WeightedIndex Constructor Example Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/weighted-sampling.md Demonstrates how to create and use a WeightedIndex sampler. This is suitable for moderate numbers of items with static weights where a few samples are needed. ```rust use rand::distr::weighted::WeightedIndex; use rand::prelude::*; let weights = vec![1, 2, 3, 4]; let weighted_index = WeightedIndex::new(&weights).unwrap(); let mut rng = rand::rng(); for _ in 0..10 { let index: usize = weighted_index.sample(&mut rng); println!("Selected index: {}", index); } ``` -------------------------------- ### Basic Normal Distribution Sampling Example Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/normal-distribution.md Demonstrates creating a Normal distribution with a specified mean and standard deviation, then sampling a value from it. ```rust use rand_distr::{Normal, Distribution}; use rand::prelude::*; let normal = Normal::new(2.0, 3.0).unwrap(); let mut rng = rand::rng(); let value = normal.sample(&mut rng); println!("{} is from N(2, 9) distribution", value); ``` -------------------------------- ### WeightedTreeIndex Usage Example Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/weighted-sampling.md Demonstrates creating a WeightedTreeIndex, sampling from it, updating weights, and sampling again with the modified distribution. ```rust use rand_distr::weighted::WeightedTreeIndex; use rand::prelude::*; let mut tree = WeightedTreeIndex::new(vec![1.0, 2.0, 3.0]).unwrap(); let mut rng = rand::rng(); // Sample from initial distribution for _ in 0..5 { let index = tree.sample(&mut rng); println!("Selected index: {}", index); } // Update weights dynamically tree.update(1, 5.0).unwrap(); // Sample again with new weights for _ in 0..5 { let index = tree.sample(&mut rng); println!("Selected index (updated): {}", index); } ``` -------------------------------- ### WeightedAliasIndex Usage Example Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/weighted-sampling.md Demonstrates how to create a WeightedAliasIndex and sample from it multiple times. Requires importing WeightedAliasIndex and a random number generator. ```rust use rand_distr::weighted::WeightedAliasIndex; use rand::prelude::*; let weights = vec![1.0, 2.0, 3.0, 4.0]; let alias_index = WeightedAliasIndex::new(weights).unwrap(); let mut rng = rand::rng(); for _ in 0..1000 { let index: usize = alias_index.sample(&mut rng); println!("Selected index: {}", index); } ``` -------------------------------- ### Normal Distribution Sampling using Coefficient of Variation Example Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/normal-distribution.md Shows how to construct a Normal distribution using the `from_mean_cv` method and then sample a value. ```rust use rand_distr::{Normal, Distribution}; let normal = Normal::from_mean_cv(1024.0, 0.1).unwrap(); let value = normal.sample(&mut rand::rng()); println!("Mean=1024, StdDev=102.4: {}", value); ``` -------------------------------- ### LogNormal Example: Linear-space Construction Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/normal-distribution.md Demonstrates constructing a LogNormal distribution using linear-space parameters (mean and coefficient of variation) and sampling a value. ```rust use rand_distr::{LogNormal, Distribution}; // Mean = e^1.5, Coefficient of variation = sqrt(e-1) let log_normal = LogNormal::from_mean_cv(4.48, 1.65).unwrap(); let value = log_normal.sample(&mut rand::rng()); println!("{}", value); ``` -------------------------------- ### Reproducible Random Number Generation Setup Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/configuration.md Demonstrates how to set up a reproducible random number generation sequence using a fixed seed and specific distribution parameters. Avoid the `std_math` feature and use `libm` for cross-platform consistency. ```rust use rand::SeedableRng; use rand_pcg::Pcg64; use rand_distr::Normal; // Reproducible setup let mut rng = Pcg64::seed_from_u64(42); let normal = Normal::new(0.0, 1.0).unwrap(); // Always produces the same sequence for _ in 0..100 { let value = normal.sample(&mut rng); println!("{}", value); } ``` -------------------------------- ### Zipf Distribution Example: Word Frequency Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/discrete-distributions.md Demonstrates creating and sampling from a Zipf distribution for modeling word frequencies, using typical parameters for language. ```rust use rand_distr::{Zipf, Distribution}; // 10000 words, s=1.5 (typical for language) let zipf: Zipf = Zipf::new(10000, 1.5).unwrap(); let word_rank = zipf.sample(&mut rand::rng()); println!("Word rank: {}", word_rank); ``` -------------------------------- ### Example: Retry attempts Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/discrete-distributions.md Demonstrates sampling from the StandardGeometric distribution (p=0.5) to simulate the number of attempts needed for a 50% success rate. ```rust use rand_distr::{StandardGeometric, Distribution}; // 50% success rate per attempt let geometric = StandardGeometric; let attempts = geometric.sample(&mut rand::rng()); println!("Attempts needed: {}", attempts); ``` -------------------------------- ### Example: Dice rolls until 6 Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/discrete-distributions.md Demonstrates sampling from a Geometric distribution to simulate the number of dice rolls required to get a 6. The probability of success (rolling a 6) is 1/6. ```rust use rand_distr::{Geometric, Distribution}; // P(success) = 1/6 (rolling a 6) let geometric = Geometric::new(1.0/6.0).unwrap(); let rolls_to_six = geometric.sample(&mut rand::rng()); println!("Rolls until six: {}", rolls_to_six); ``` -------------------------------- ### LogNormal Example: Correlated Samples Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/normal-distribution.md Shows how to generate correlated samples from two LogNormal distributions by using the same z-score. ```rust use rand::prelude::*; use rand_distr::{LogNormal, StandardNormal}; let mut rng = rand::rng(); let z = StandardNormal.sample(&mut rng); let x1 = LogNormal::from_mean_cv(3.0, 1.0).unwrap().from_zscore(z); let x2 = LogNormal::from_mean_cv(2.0, 4.0).unwrap().from_zscore(z); ``` -------------------------------- ### Enable Alloc Feature in Cargo.toml Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/configuration.md This example shows how to enable the 'alloc' feature for rand_distr. The 'alloc' feature is required for using multivariate distributions and weighted distributions that rely on heap allocations. ```toml rand_distr = { version = "0.6", features = [""] } ``` -------------------------------- ### Example: Quality Control Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/discrete-distributions.md Illustrates sampling the number of defects found when inspecting 10 items from a batch of 100, where 5 items are known to be defective. ```rust use rand_distr::{Hypergeometric, Distribution}; // Batch of 100 items, 5 are defective, inspect 10 let hg = Hypergeometric::new(100, 5, 10).unwrap(); let defects = hg.sample(&mut rand::rng()); println!("Defects found: {}", defects); ``` -------------------------------- ### Example: Deck of Cards Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/discrete-distributions.md Demonstrates sampling the number of hearts drawn from a standard deck of 52 cards when drawing 5 cards without replacement. ```rust use rand_distr::{Hypergeometric, Distribution}; // Standard deck: 52 cards, 13 hearts, draw 5 let hg = Hypergeometric::new(52, 13, 5).unwrap(); let hearts = hg.sample(&mut rand::rng()); println!("Hearts drawn: {}", hearts); ``` -------------------------------- ### Serialize and Deserialize Distribution with Serde Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/configuration.md Example of using the 'serde' feature to serialize a Normal distribution to JSON and then deserialize it back. This showcases saving, restoring, or transmitting distribution states. ```rust use rand_distr::Normal; use serde_json; let normal = Normal::new(0.0, 1.0).unwrap(); let json = serde_json::to_string(&normal).unwrap(); println!("{}", json); let restored: Normal = serde_json::from_str(&json).unwrap(); ``` -------------------------------- ### Poisson Distribution Example: Website Traffic Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/discrete-distributions.md Simulates website visits per minute using a Poisson distribution with a specified average rate. The sample is cast to `u32` for practical counting. ```rust use rand_distr::{Poisson, Distribution}; // Average 5 visits per minute let poisson = Poisson::new(5.0).unwrap(); let mut rng = rand::rng(); for minute in 1..=60 { let visits = poisson.sample(&mut rng) as u32; println!("Minute {}: {} visits", minute, visits); } ``` -------------------------------- ### Binomial Distribution Example: Coin Flips Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/discrete-distributions.md Simulates the number of heads in a series of coin flips using the Binomial distribution. Requires importing `Binomial` and `Distribution` traits. ```rust use rand_distr::{Binomial, Distribution}; // 10 coin flips, fair coin (p = 0.5) let binomial = Binomial::new(10, 0.5).unwrap(); let heads = binomial.sample(&mut rand::rng()); println!("Heads: {}", heads); ``` -------------------------------- ### WeightedAliasIndex - Static Weights, Many Samples Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/weighted-sampling.md Constructs a WeightedAliasIndex for static weights when many samples are needed. This offers efficient sampling after an initial setup cost. ```APIDOC ## WeightedAliasIndex::new ### Description Creates a new `WeightedAliasIndex` distribution from a vector of weights. This is optimized for drawing many samples from static weights. ### Method `WeightedAliasIndex::new(weights: Vec) -> Result, WeightedError>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **weights** (Vec of `F` where `F` implements `num_traits::Float`) - Required - A vector containing the weights for each item. ### Request Example ```rust use rand_distr::weighted::WeightedAliasIndex; let weights = vec![1.0, 2.0, 3.0, 4.0]; let index = WeightedAliasIndex::new(weights).unwrap(); ``` ### Response #### Success Response (Result) - **WeightedAliasIndex** - A distribution optimized for many samples. #### Response Example ```rust // Successful creation of WeightedAliasIndex let index = WeightedAliasIndex::new(weights).unwrap(); ``` #### Error Response (WeightedError) - **WeightedError::NoItem** - If the `weights` sequence is empty. - **WeightedError::InvalidWeight** - If any weight is not finite or is negative. - **WeightedError::TooLarge** - If the total weight is too large to represent. ``` -------------------------------- ### Handling NaN and Infinite Parameters Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/errors.md Distributions reject NaN and infinite values in their parameters. This example demonstrates asserting that creating a Normal distribution with NaN or infinite standard deviation results in an error. ```rust use rand_distr::Normal; let normal = Normal::new(f64::NAN, 1.0); assert!(normal.is_err()); // BadVariance let normal = Normal::new(0.0, f64::INFINITY); assert!(normal.is_err()); // BadVariance ``` -------------------------------- ### Generating Correlated Normal Samples Example Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/normal-distribution.md Illustrates generating correlated samples from two different Normal distributions by using the same z-score obtained from StandardNormal. ```rust use rand::prelude::*; use rand_distr::{Normal, StandardNormal}; let mut rng = rand::rng(); let z = StandardNormal.sample(&mut rng); let x1 = Normal::new(0.0, 1.0).unwrap().from_zscore(z); let x2 = Normal::new(2.0, 3.0).unwrap().from_zscore(z); // x1 and x2 are positively correlated ``` -------------------------------- ### Binomial Distribution Example: Defective Items Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/discrete-distributions.md Models the number of defective items in a batch using the Binomial distribution. Specify the total number of items and the defect rate. ```rust use rand_distr::{Binomial, Distribution}; // 100 items, 2% defect rate let binomial = Binomial::new(100, 0.02).unwrap(); let defects = binomial.sample(&mut rand::rng()); println!("Defects: {}", defects); ``` -------------------------------- ### Creating a UnitDisc Sample Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/multivariate-distributions.md Demonstrates how to create a sample from the UnitDisc distribution. ```rust use rand_distr::UnitDisc; let sample: [f64; 2] = UnitDisc.sample(&mut rng); ``` -------------------------------- ### Create UnitSphere Instance Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/multivariate-distributions.md Demonstrates how to create a UnitSphere distribution and sample from it. ```rust use rand_distr::UnitSphere; let sample: [f64; 3] = UnitSphere.sample(&mut rng); ``` -------------------------------- ### Poisson Distribution Example: Rare Events Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/discrete-distributions.md Models the occurrence of rare events over a period using the Poisson distribution. This example calculates the number of disasters in a decade based on a low average annual rate. ```rust use rand_distr::{Poisson, Distribution}; // Average 0.1 disasters per year let poisson = Poisson::new(0.1).unwrap(); let disasters_in_decade = poisson.sample(&mut rand::rng()) as u32; println!("Disasters in 10 years: {}", disasters_in_decade); ``` -------------------------------- ### Create UnitCircle Sample Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/multivariate-distributions.md Demonstrates how to create a sample from the UnitCircle distribution. ```rust use rand_distr::UnitCircle; let sample: [f64; 2] = UnitCircle.sample(&mut rng); ``` -------------------------------- ### Create UnitBall Sample Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/multivariate-distributions.md Demonstrates how to create a sample from the UnitBall distribution. ```rust use rand_distr::UnitBall; let sample: [f64; 3] = UnitBall.sample(&mut rng); ``` -------------------------------- ### Exp1 Creation and Sampling Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/exponential-gamma.md Demonstrates how to create and sample from the Exp1 distribution. ```rust use rand_distr::Exp1; let sample: f64 = Exp1.sample(&mut rng); ``` -------------------------------- ### Basic Gamma Sampling Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/exponential-gamma.md Demonstrates how to create a Gamma distribution with shape 2.0 and scale 5.0, and then sample a value from it. ```rust use rand_distr::{Gamma, Distribution}; let gamma = Gamma::new(2.0, 5.0).unwrap(); let value = gamma.sample(&mut rand::rng()); println!("{} is from Gamma(2, 5)", value); ``` -------------------------------- ### StandardNormal Creation and Sampling Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/normal-distribution.md Demonstrates how to create and sample from the StandardNormal distribution. No explicit constructor is needed; use the struct directly and call the sample method. ```rust use rand_distr::StandardNormal; let sample: f64 = StandardNormal.sample(&mut rng); ``` -------------------------------- ### Beta Distribution Constructor and Sampling Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/other-continuous.md Instantiate a Beta distribution with specified shape parameters and sample values from it. Ensure alpha and beta are positive. ```rust use rand_distr::{Beta, Distribution}; let beta = Beta::new(2.0, 5.0).unwrap(); let value = beta.sample(&mut rand::rng()); println!("{} from Beta(2, 5)", value); ``` -------------------------------- ### Standard rand_distr Configuration (Default) Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/configuration.md This is the default configuration for most applications, including everything except serde support. ```toml rand_distr = { version = "0.6" } ``` -------------------------------- ### Platform-Independent Floating-Point Exponentiation (libm) Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/configuration.md Demonstrates the default platform-independent behavior of the `exp` function using `num_traits` with the `libm` feature. ```rust // Default behavior (with libm) let exp_result = num_traits::float::FloatCore::exp(x); // Same result on all platforms ``` -------------------------------- ### Sample from Fixed Categorical Distribution Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/weighted-sampling.md Demonstrates how to create a WeightedAliasIndex from a slice of weights and sample from it. Ensure weights are valid before creating the index. ```rust use rand::prelude::*; use rand_distr::weighted::WeightedAliasIndex; // Example 1: Fixed categorical distribution fn sample_from_categories(weights: &[f64]) -> usize { let index = WeightedAliasIndex::new(weights.to_vec()).unwrap(); index.sample(&mut rand::rng()) } ``` -------------------------------- ### WeightedIndex Constructor and Usage Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/weighted-sampling.md Demonstrates how to create and use the WeightedIndex sampler with a vector of weights. ```APIDOC ## WeightedIndex ### Description Binary-search based weighted index sampling. ### Constructor ```rust pub fn new(weights: I) -> Result, WeightedError> where I: IntoIterator, I::Item: AsRef, F: Weight + for<'a> std::ops::AddAssign<&'a F>, ``` ### Example ```rust use rand::distr::weighted::WeightedIndex; use rand::prelude::*; let weights = vec![1, 2, 3, 4]; let weighted_index = WeightedIndex::new(&weights).unwrap(); let mut rng = rand::thread_rng(); for _ in 0..10 { let index: usize = weighted_index.sample(&mut rng); println!("Selected index: {}", index); } ``` ### Performance - Construction: O(n log w) where w is the weight range - Sampling: O(log n) per sample - Memory: O(n) - Best when: Few samples needed, static weights ``` -------------------------------- ### Efficient Sampling with sample_to_slice Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/multivariate-distributions.md Shows how to use `sample_to_slice` for efficient sampling, avoiding extra allocations by filling a pre-allocated buffer. ```rust use rand_distr::{Dirichlet, MultiDistribution}; let alphas = vec![2.0, 3.0, 1.0]; let dirichlet: Dirichlet = Dirichlet::new(&alphas).unwrap(); let mut rng = rand::rng(); let mut output = vec![0.0; 3]; dirichlet.sample_to_slice(&mut rng, &mut output); println!("Allocations avoided: {:?}", output); ``` -------------------------------- ### Documentation Build Configuration for `rand_distr` Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/configuration.md Configure `Cargo.toml` to include specific features and rustdoc arguments for the `docs.rs` build. This ensures all distributions are documented, serialization support is included, and direct links to source code definitions are available. ```toml [package.metadata.docs.rs] features = ["serde"] rustdoc-args = ["--generate-link-to-definition"] ``` -------------------------------- ### Poisson Distribution Constructor Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/discrete-distributions.md Create a Poisson distribution using `Poisson::new`, providing the rate parameter `lambda`. Lambda must be positive and finite. ```rust pub fn new(lambda: F) -> Result, Error> ``` -------------------------------- ### Rand Distr Documentation Overview Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/GENERATION_SUMMARY.txt This snippet provides a high-level overview of the rand_distr crate's documentation, including the types of errors and features documented, the organization of content, quality metrics, and key features. ```APIDOC ## Rand Distr Documentation Summary ### Description This document summarizes the API documentation for the rand_distr crate, detailing its structure, content, and quality. ### Content Organization: - **Main Reference**: README.md - **Type Reference**: types.md - **Error Reference**: errors.md - **Configuration**: configuration.md - **By Distribution Family (api-reference/)**: - Normal family: normal-distribution.md - Exponential family: exponential-gamma.md - Discrete: discrete-distributions.md - Multivariate: multivariate-distributions.md - Other continuous: other-continuous.md - Weighted sampling: weighted-sampling.md - Master overview: distributions-overview.md ### Key Features of Documentation: - **Comprehensive Coverage**: Every exported type, constructor, error, and feature is documented. - **Practical Examples**: Includes basic and advanced usage, error handling, and configuration examples. - **Precise Technical Details**: Exact type signatures, parameter requirements, return types, and trait implementations. - **Mathematical Context**: Density/probability mass functions, distribution properties, algorithms, and literature references. - **Easy Navigation**: Master overview, file index, quick reference, and cross-references. - **Configuration Guidance**: Feature matrix, platform-specific behavior, reproducibility, and performance considerations. ### Usage Guide: - **Start Here**: Open README.md, use the index to find distribution families, and jump to specific guides. - **For Complete Details**: Start with distributions-overview.md, then specific distribution guides, types.md, errors.md. ``` -------------------------------- ### Chi-squared Distribution via Gamma Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/exponential-gamma.md Shows how to obtain a Chi-squared distribution sample by using a Gamma distribution with specific parameters (shape k/2, scale 2). ```rust use rand_distr::{Gamma, Distribution}; // χ²(k) = Gamma(k/2, 2) let chi_sq = Gamma::new(5.0, 2.0).unwrap(); // χ²(10) let value = chi_sq.sample(&mut rand::rng()); println!("Chi-squared sample: {}", value); ``` -------------------------------- ### LogNormal Constructor (Log-space) Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/normal-distribution.md Creates a new LogNormal distribution using log-space parameters (mean and standard deviation of ln(X)). Sigma must be finite. ```rust pub fn new(mu: F, sigma: F) -> Result, Error> ``` -------------------------------- ### Converting Poisson f64 Result to u64 Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/discrete-distributions.md Illustrates how to sample from a Poisson distribution with f64 parameters and then cast the resulting floating-point value to a u64 count. ```rust let poisson_f64: f64 = Poisson::new(5.0).unwrap().sample(&mut rng); let count: u64 = poisson_f64 as u64; ``` -------------------------------- ### Enable Alloc Feature for Rand_distr Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/configuration.md Add this to your Cargo.toml to resolve 'cannot find module `multi`' errors by ensuring the 'alloc' feature is enabled. ```toml rand_distr = { version = "0.6", features = ["alloc"] } ``` -------------------------------- ### WeightedIndex - Static Weights, Few Samples Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/weighted-sampling.md Constructs a WeightedIndex for static weights when few samples are needed. It takes a slice of weights and returns a distribution that can be sampled from. ```APIDOC ## WeightedIndex::new ### Description Creates a new `WeightedIndex` distribution from a slice of weights. This is suitable for static weights and drawing a few samples. ### Method `WeightedIndex::new(weights: &[W]) -> Result, WeightedError>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **weights** (slice of `W` where `W` implements `rand::distributions::weighted::Weight`) - Required - A slice containing the weights for each item. ### Request Example ```rust use rand::distr::weighted::WeightedIndex; let weights = vec![1, 2, 3, 4]; let index = WeightedIndex::new(&weights).unwrap(); ``` ### Response #### Success Response (Result) - **WeightedIndex** - A distribution that can be sampled. #### Response Example ```rust // Successful creation of WeightedIndex let index = WeightedIndex::new(&weights).unwrap(); ``` #### Error Response (WeightedError) - **WeightedError::NoItem** - If the `weights` sequence is empty. - **WeightedError::InvalidWeight** - If any weight is not finite or is negative. - **WeightedError::TooLarge** - If the total weight is too large to represent. ``` -------------------------------- ### UnitCircle Sample Method Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/multivariate-distributions.md Signature for the sample method of UnitCircle, returning a 2D vector. ```rust fn sample(&self, rng: &mut R) -> [F; 2] ``` -------------------------------- ### Sample from UnitSphere Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/multivariate-distributions.md Illustrates sampling a 3D vector uniformly distributed on the unit sphere surface. ```rust fn sample(&self, rng: &mut R) -> [F; 3] ``` -------------------------------- ### Adaptive Sampling with Dynamic Weight Adjustment Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/weighted-sampling.md Shows how to use WeightedTreeIndex for adaptive sampling where weights can be updated dynamically. This is useful for scenarios requiring adjustments based on outcomes. ```rust use rand::prelude::*; use rand_distr::weighted::WeightedTreeIndex; // Example 2: Dynamic weight adjustment fn adaptive_sampling() { let mut weights = vec![1.0, 1.0, 1.0]; let mut index = WeightedTreeIndex::new(weights.clone()).unwrap(); let mut rng = rand::rng(); for round in 0..10 { let selected = index.sample(&mut rng); // Increase weight of successful item let new_weight = (round + 1) as f64; index.update(selected, new_weight).unwrap(); } } ``` -------------------------------- ### Sample Proportions from Dirichlet Distribution Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/multivariate-distributions.md Demonstrates sampling proportions from a Dirichlet distribution with equal concentration parameters. Requires importing Dirichlet, Distribution, and MultiDistribution traits. ```rust use rand_distr::{Dirichlet, Distribution, MultiDistribution}; // 3 categories with equal concentration let alphas = vec![1.0, 1.0, 1.0]; let dirichlet: Dirichlet = Dirichlet::new(&alphas).unwrap(); let mut rng = rand::rng(); let proportions = dirichlet.sample(&mut rng); println!("Proportions: {:?}", proportions); // Output example: [0.234, 0.512, 0.254] ``` -------------------------------- ### Normal Distribution Sampling Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/normal-distribution.md Illustrates how to sample a single value from a defined Normal distribution using the `sample` method. ```rust fn sample(&self, rng: &mut R) -> F ``` -------------------------------- ### Constructing a Normal Distribution Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/configuration.md Configure a Normal distribution by providing its mean (location) and standard deviation (scale) as constructor parameters. This is not a runtime configuration. ```rust use rand_distr::Normal; let normal = Normal::new( mean, // μ - Location parameter std_dev, // σ - Scale parameter )?; ``` -------------------------------- ### Zipf Constructor Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/discrete-distributions.md Creates a new Zipf distribution. Requires n >= 1 and a finite s >= 0. ```rust pub fn new(n: u64, s: F) -> Result, Error> ``` -------------------------------- ### Exp Constructor Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/exponential-gamma.md Shows the signature for the `new` constructor of the Exp distribution, which takes the rate parameter lambda. ```rust pub fn new(lambda: F) -> Result, Error> ``` -------------------------------- ### Platform-Specific Floating-Point Exponentiation (std_math) Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/configuration.md Shows how to use the `std_math` feature for floating-point exponentiation, which may yield slightly different results across platforms. ```rust // With std_math feature let exp_result = std::f64::exp(x); // May differ slightly between platforms ``` -------------------------------- ### Sample from Normal Distribution Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/README.md Demonstrates sampling a single value from a normal distribution with a specified mean and standard deviation. Requires `rand` and `rand_distr` crates. ```rust use rand::prelude::* use rand_distr::Normal let mut rng = rand::rng() let normal = Normal::new(0.0, 1.0)? let value = normal.sample(&mut rng) println!("Sample: {}", value) ``` -------------------------------- ### PertBuilder Methods Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/types.md Provides methods to construct a Pert distribution, including setting the shape. Returns a Result containing either the Pert distribution or an Error. ```rust pub struct PertBuilder where F: Float, { // private fields } // Methods: // - `new(min, likeliest, max) -> Result` // - `shape(shape: F) -> Self` // - `build() -> Result, Error>` ``` -------------------------------- ### Sample from Poisson Distribution Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/README.md Shows how to sample multiple counts from a Poisson distribution with a given rate parameter (lambda). Useful for modeling event counts. ```rust use rand::prelude::* use rand_distr::{Poisson, Distribution} let mut rng = rand::rng() let poisson = Poisson::new(5.0)? for _ in 0..10 { let count: u64 = poisson.sample(&mut rng) as u64 println!("Count: {}", count) } ``` -------------------------------- ### Normal Distribution Equality Check Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/normal-distribution.md Demonstrates how to check for equality between two Normal distribution instances. Ensure the distributions are created with the same mean and standard deviation. ```rust let n1 = Normal::new(1.0, 2.0).unwrap(); let n2 = Normal::new(1.0, 2.0).unwrap(); assert_eq!(n1, n2); ``` -------------------------------- ### Cauchy Distribution Constructor Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/other-continuous.md Instantiate a Cauchy distribution with a specified location and scale. The scale parameter must be positive. ```rust pub fn new(location: F, scale: F) -> Result, Error> ``` -------------------------------- ### SkewNormal Constructor and Sampling Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/other-continuous.md Instantiate a SkewNormal distribution with specified location, scale, and shape parameters. Then, generate a sample from this distribution using a random number generator. Ensure the scale parameter is positive. ```rust use rand_distr::{SkewNormal, Distribution}; let skew_normal = SkewNormal::new(0.0, 1.0, 2.0).unwrap(); let value = skew_normal.sample(&mut rand::rng()); println!("Skew normal sample: {}", value); ``` -------------------------------- ### Enable Serde Feature in Cargo.toml Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/configuration.md This TOML snippet demonstrates how to enable the 'serde' feature for the rand_distr crate. Enabling this feature allows for the serialization and deserialization of distribution types using the serde library. ```toml rand_distr = { version = "0.6", features = ["serde"] } ``` -------------------------------- ### Hypergeometric Constructor Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/discrete-distributions.md Creates a new Hypergeometric distribution. Ensure that successes and draws do not exceed the total population size. ```rust pub fn new(population: u64, successes: u64, draws: u64) -> Result ``` -------------------------------- ### LogNormal Constructor (Linear-space) Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/normal-distribution.md Creates a new LogNormal distribution using linear-space parameters (actual mean and coefficient of variation). Mean must be positive, and CV non-negative. Handles the special case of mean=0, cv=0. ```rust pub fn from_mean_cv(mean: F, cv: F) -> Result, Error> ``` -------------------------------- ### Normal Constructor from Mean and Coefficient of Variation Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/normal-distribution.md Demonstrates the `from_mean_cv` constructor, which creates a Normal distribution using the mean and the coefficient of variation (cv = abs(σ / μ)). ```rust pub fn from_mean_cv(mean: F, cv: F) -> Result, Error> ``` -------------------------------- ### Frechet Distribution Constructor Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/other-continuous.md Creates a new Frechet distribution with specified scale and shape parameters. Returns an error if parameters are invalid. ```rust pub fn new(scale: F, shape: F) -> Result, Error> ``` -------------------------------- ### Pareto Distribution Constructor Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/other-continuous.md Creates a new Pareto distribution with specified scale and shape parameters. Returns an error if scale or shape are non-positive or NaN. ```rust pub fn new(scale: F, shape: F) -> Result, Error> ``` -------------------------------- ### Conditional Compilation for Alloc Feature Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/configuration.md Demonstrates using conditional compilation (`#[cfg(feature = "alloc")]`) to check for the `alloc` feature and its usage in creating a Dirichlet distribution. ```rust #[cfg(feature = "alloc")] fn requires_alloc() { let dirichlet = rand_distr::multi::Dirichlet::new(&[1.0, 2.0, 3.0]).unwrap(); } ``` -------------------------------- ### Zeta Distribution Sample Method Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/other-continuous.md Samples a value from the Zeta distribution using a provided random number generator. Returns a u64. ```rust fn sample(&self, rng: &mut R) -> u64 ``` -------------------------------- ### PERT Distribution Constructor via Builder Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/other-continuous.md Constructs a PERT distribution using the builder pattern, specifying min, likeliest, and max values. An optional shape can also be provided. ```rust let pert = PertBuilder::new(min, likeliest, max) .unwrap() .build() .unwrap(); ``` ```rust let pert = PertBuilder::new(min, likeliest, max) .unwrap() .shape(4.0) .build() .unwrap(); ``` -------------------------------- ### Gamma Constructor Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/exponential-gamma.md Creates a new Gamma distribution with specified shape (k) and scale (θ) parameters. Both parameters must be positive. ```rust pub fn new(shape: F, scale: F) -> Result, Error> ``` -------------------------------- ### Hypergeometric Constructor Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/discrete-distributions.md Creates a new Hypergeometric distribution. It models sampling without replacement from a population. ```APIDOC ## new ### Description Creates a new Hypergeometric distribution. ### Signature ```rust pub fn new(population: u64, successes: u64, draws: u64) -> Result ``` ### Parameters #### Path Parameters - **population** (u64) - Required - Total population size (N) - **successes** (u64) - Required - Number of success states in population (K) - **draws** (u64) - Required - Number of draws without replacement (n) ### Constraints - `successes ≤ population` - `draws ≤ population` ### Returns - `Ok(Hypergeometric)` on success. - `Err(Error)` if parameters are invalid (e.g., `TooLarge`, `SuccessesTooLarge`, `DrawsTooLarge`). ``` -------------------------------- ### Zipf::sample Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/discrete-distributions.md Samples a value from the Zipf distribution. The returned value is a rank between 1 and n (inclusive). ```APIDOC ## Zipf::sample ### Description Samples a value from the Zipf distribution. The returned value is a rank between 1 and n (inclusive). ### Method Signature `fn sample(&self, rng: &mut R) -> u64` ### Parameters #### Path Parameters - **rng** (`&mut R`) - Required - A mutable reference to a random number generator implementing the `Rng` trait. ### Returns - `u64` - A sampled value in the range [1, n]. ### Example ```rust use rand_distr::{Zipf, Distribution}; let zipf: Zipf = Zipf::new(10000, 1.5).unwrap(); let mut rng = rand::thread_rng(); let word_rank = zipf.sample(&mut rng); println!("Word rank: {}", word_rank); ``` ``` -------------------------------- ### Gumbel::sample Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/other-continuous.md Returns a sample from the Gumbel distribution. ```APIDOC ## Gumbel::sample ### Description Returns a sample from the Gumbel distribution using the provided random number generator. ### Method ```rust fn sample(&self, rng: &mut R) -> F ``` ### Parameters - `rng` (*mut R) - A mutable reference to a random number generator. ### Returns - `F` - A sample from the Gumbel distribution. ### Examples ```rust use rand_distr::{Gumbel, Distribution}; let gumbel = Gumbel::new(0.0, 1.0).unwrap(); let value = gumbel.sample(&mut rand::rng()); println!("Gumbel sample: {}", value); ``` ``` -------------------------------- ### Enable Std Math Feature in Cargo.toml Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/configuration.md Configure Cargo.toml to enable the 'std_math' feature for rand_distr. This directs the crate to use floating-point functions from the standard library instead of libm, potentially improving performance at the cost of cross-platform reproducibility. ```toml rand_distr = { version = "0.6", features = ["std_math"] } ``` -------------------------------- ### Weighted Sampling with Alias Index Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/README.md Illustrates weighted sampling using the `WeightedAliasIndex` for efficient O(1) selection of indices based on provided weights. Suitable for scenarios where items have different probabilities of being chosen. ```rust use rand::prelude::* use rand_distr::weighted::WeightedAliasIndex let weights = vec![1.0, 2.0, 3.0, 4.0] let index_dist = WeightedAliasIndex::new(weights)? let mut rng = rand::rng() for _ in 0..100 { let idx = index_dist.sample(&mut rng) println!("Selected index: {}", idx) } ``` -------------------------------- ### Gamma Distribution Constructor Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/exponential-gamma.md Constructs a new Gamma distribution with specified shape and scale parameters. The shape and scale must be positive. ```APIDOC ## new ### Description Constructs a new Gamma distribution with the given shape (k) and scale (θ) parameters. ### Method `new(shape: F, scale: F) -> Result, Error>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **shape** (F) - Required - Shape parameter (k), must be positive. - **scale** (F) - Required - Scale parameter (θ), must be positive and not too large. ### Request Example ```rust use rand_distr::Gamma; let gamma_distribution = Gamma::::new(2.0, 5.0); ``` ### Response #### Success Response (Result, Error>) - **Ok(Gamma)**: A new Gamma distribution instance if parameters are valid. - **Err(Error)**: An error if shape or scale parameters are invalid. #### Error Type ```rust pub enum Error { ShapeTooSmall, // shape <= 0 or NaN ScaleTooSmall, // scale <= 0 or NaN ScaleTooLarge, // 1 / scale == 0 } ``` ### Response Example ```rust // Successful creation let gamma = Gamma::new(2.0, 5.0).unwrap(); // Example of an error case let invalid_gamma = Gamma::::new(-1.0, 5.0); match invalid_gamma { Ok(_) => println!("Distribution created successfully."), Err(Error::ShapeTooSmall) => println!("Error: Shape parameter must be positive."), _ => {} } ``` ``` -------------------------------- ### LogNormal::new Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/normal-distribution.md Constructs a LogNormal distribution using log-space parameters (mean and standard deviation of ln(X)). ```APIDOC ## LogNormal::new ### Description Constructs a LogNormal distribution using log-space parameters. ### Method `LogNormal::new(mu: F, sigma: F) -> Result, Error>` ### Parameters #### Path Parameters - `mu` (F) - Required - Mean of ln(X), unrestricted - `sigma` (F) - Required - Standard deviation of ln(X), must be finite ### Request Example ```rust use rand_distr::LogNormal; let log_normal = LogNormal::new(2.0, 3.0).unwrap(); ``` ``` -------------------------------- ### no_std Support with Alloc Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/configuration.md Enable this configuration to use rand_distr in a no_std environment when the 'alloc' crate is available. ```rust #![no_std] extern crate alloc; // if needed use rand_distr::Normal; // Works in no_std + alloc ``` -------------------------------- ### Monte Carlo Integration on Sphere Surface Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/multivariate-distributions.md Performs Monte Carlo integration on the sphere surface by sampling points and evaluating a function. Requires `rand_distr` and `rand` crates. ```rust use rand_distr::{UnitSphere, Distribution}; use std::f64::consts::PI; let mut rng = rand::rng(); let samples = 100_000; let mut sum = 0.0; for _ in 0..samples { let [x, y, z]: [f64; 3] = UnitSphere.sample(&mut rng); // Evaluate some function on the sphere sum += (x * x + y * y).sqrt(); } let average = sum / samples as f64; println!("Average: {}", average); ``` -------------------------------- ### Normal Constructor Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/normal-distribution.md Shows the signature for the `new` constructor of the Normal distribution. It takes the mean and standard deviation, returning an error if the standard deviation is non-finite. ```rust pub fn new(mean: F, std_dev: F) -> Result, Error> ``` -------------------------------- ### Binomial Distribution Constructor Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/discrete-distributions.md Use the `Binomial::new` constructor to create a Binomial distribution. Ensure `n` is greater than 0 and `p` is within the [0, 1] range to avoid errors. ```rust pub fn new(n: u64, p: f64) -> Result ``` -------------------------------- ### Zeta Distribution Constructor Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/other-continuous.md Creates a new Zeta distribution with the specified shape parameter. Returns an error if the shape parameter is invalid. ```rust pub fn new(s: F) -> Result, Error> ``` -------------------------------- ### Using MultiDistribution with Dirichlet Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/multivariate-distributions.md Demonstrates the usage pattern of the MultiDistribution trait with a Dirichlet distribution, sampling directly into a pre-allocated vector to avoid allocations. ```rust use rand_distr::multi::MultiDistribution; let dist = Dirichlet::new(&[1.0, 2.0, 3.0]).unwrap(); let mut output = vec![0.0; dist.sample_len()]; dist.sample_to_slice(&mut rng, &mut output); ``` -------------------------------- ### Triangular Distribution Constructor Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/other-continuous.md Creates a new Triangular distribution with specified minimum, mode, and maximum values. Returns an error if the mode is out of bounds or min is greater than max. ```rust pub fn new(min: F, mode: F, max: F) -> Result, Error> ``` -------------------------------- ### PertBuilder Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/types.md A builder for constructing Pert distributions. It allows setting shape and then building the distribution. ```APIDOC ## PertBuilder ### Description A builder for constructing Pert distributions. It allows setting shape and then building the distribution. ### Type ```rust pub struct PertBuilder where F: Float, { // private fields } ``` ### Methods - `new(min, likeliest, max) -> Result` - `shape(shape: F) -> Self` - `build() -> Result, Error>` ``` -------------------------------- ### Geometric Constructor Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/discrete-distributions.md Creates a new Geometric distribution. The probability 'p' must be in the range (0, 1]. ```rust pub fn new(p: f64) -> Result ``` -------------------------------- ### Conditional Sampling Implementations Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/configuration.md Use these configurations to select between high-performance sampling with std_math or platform-independent, reproducible sampling without it. ```rust #[cfg(feature = "std_math")] fn fast_sampling() { // High-performance sampling } ``` ```rust #[cfg(not(feature = "std_math"))] fn reproducible_sampling() { // Platform-independent, reproducible sampling } ``` -------------------------------- ### Multivariate Distributions Source: https://github.com/rust-random/rand_distr/blob/master/_autodocs/api-reference/distributions-overview.md Provides constructors for multivariate probability distributions. ```APIDOC ## Multivariate Distributions Distributions that produce multi-dimensional samples. | Type | Constructor | Parameters | Notes | |---|---|---|---| | [`Dirichlet`] | `Dirichlet::new(alphas)?` | `alphas: &[F]` | Dirichlet distribution (requires `alloc` feature) | | [`UnitSphere`] | — | — | Uniform on unit sphere surface | | [`UnitBall`] | — | — | Uniform inside unit ball | | [`UnitCircle`] | — | — | Uniform on unit circle | | [`UnitDisc`] | — | — | Uniform inside unit disc | ```