pub struct Uncertain<T> {
pub sample_fn: Arc<dyn Fn() -> T + Send + Sync>,
/* private fields */
}Expand description
A type that represents uncertain data as a probability distribution using sampling-based computation with conditional semantics.
Uncertain provides a way to work with probabilistic values
by representing them as sampling functions with a computation graph
for lazy evaluation and proper uncertainty-aware conditionals.
Fields§
§sample_fn: Arc<dyn Fn() -> T + Send + Sync>The sampling function that generates values from this distribution
Implementations§
Source§impl<T> Uncertain<T>where
T: Shareable,
impl<T> Uncertain<T>where
T: Shareable,
Sourcepub fn point(value: T) -> Self
pub fn point(value: T) -> Self
Creates a point-mass distribution (certain value)
§Example
use uncertain_rs::Uncertain;
let certain_value = Uncertain::point(42.0);
assert_eq!(certain_value.sample(), 42.0);Sourcepub fn mixture(
components: Vec<Uncertain<T>>,
weights: Option<Vec<f64>>,
) -> Result<Self, &'static str>
pub fn mixture( components: Vec<Uncertain<T>>, weights: Option<Vec<f64>>, ) -> Result<Self, &'static str>
Creates a mixture of distributions with optional weights
§Arguments
components- Vector of distributions to mixweights- Optional weights for each component (uniform if None)
§Errors
Returns an error if the components vector is empty or if the weights count doesn’t match the components count.
§Panics
May panic if the components vector is empty when attempting to get the first component, which should not happen due to the input validation.
§Example
use uncertain_rs::Uncertain;
let normal1 = Uncertain::normal(0.0, 1.0);
let normal2 = Uncertain::normal(5.0, 1.0);
let mixture = Uncertain::mixture(
vec![normal1, normal2],
Some(vec![0.7, 0.3])
).unwrap();Sourcepub fn empirical(data: Vec<T>) -> Result<Self, &'static str>
pub fn empirical(data: Vec<T>) -> Result<Self, &'static str>
Creates an empirical distribution from observed data
§Arguments
data- Vector of observed data points
§Errors
Returns an error if the data vector is empty.
§Panics
May panic if the random number generator fails to select from the data, which should not happen if the data is non-empty.
§Example
use uncertain_rs::Uncertain;
let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
let empirical = Uncertain::empirical(data).unwrap();Source§impl<T> Uncertain<T>
impl<T> Uncertain<T>
Sourcepub fn categorical(
probabilities: &HashMap<T, f64>,
) -> Result<Self, &'static str>
pub fn categorical( probabilities: &HashMap<T, f64>, ) -> Result<Self, &'static str>
Creates a categorical distribution from value-probability pairs
§Arguments
probabilities- A map of values to their probabilities
§Errors
Returns an error if the probabilities map is empty.
§Panics
May panic if the cumulative probability vector is empty, which should not happen if the input validation passes.
§Example
use uncertain_rs::Uncertain;
use std::collections::HashMap;
let mut probs = HashMap::new();
probs.insert("red", 0.5);
probs.insert("blue", 0.3);
probs.insert("green", 0.2);
let color = Uncertain::categorical(&probs).unwrap();Source§impl Uncertain<f64>
impl Uncertain<f64>
Sourcepub fn uniform(min: f64, max: f64) -> Self
pub fn uniform(min: f64, max: f64) -> Self
Creates a uniform distribution
§Example
use uncertain_rs::Uncertain;
let uniform = Uncertain::uniform(0.0, 10.0);Sourcepub fn exponential(rate: f64) -> Self
pub fn exponential(rate: f64) -> Self
Sourcepub fn log_normal(mu: f64, sigma: f64) -> Self
pub fn log_normal(mu: f64, sigma: f64) -> Self
Source§impl<T> Uncertain<T>
impl<T> Uncertain<T>
Source§impl Uncertain<bool>
Evidence-based conditional methods for uncertain boolean values
impl Uncertain<bool>
Evidence-based conditional methods for uncertain boolean values
Sourcepub fn probability_exceeds(&self, threshold: f64) -> bool
pub fn probability_exceeds(&self, threshold: f64) -> bool
Evidence-based conditional using hypothesis testing
This is the core method that implements the paper’s key insight: ask about evidence, not boolean facts.
§Arguments
threshold- Probability threshold to exceedconfidence_level- Confidence level for the test (default: 0.95)max_samples- Maximum number of samples to use (default: 10000)
§Example
use uncertain_rs::{Uncertain, operations::Comparison};
let speed = Uncertain::normal(55.0, 5.0);
let speeding_evidence = Comparison::gt(&speed, 60.0);
// Only issue ticket if 95% confident speeding
if speeding_evidence.probability_exceeds(0.95) {
println!("Issue speeding ticket");
}Sourcepub fn probability_exceeds_with_params(
&self,
threshold: f64,
confidence_level: f64,
max_samples: usize,
) -> bool
pub fn probability_exceeds_with_params( &self, threshold: f64, confidence_level: f64, max_samples: usize, ) -> bool
Evidence-based conditional with configurable parameters
§Example
use uncertain_rs::Uncertain;
let condition = Uncertain::bernoulli(0.7);
let confident = condition.probability_exceeds_with_params(0.6, 0.99, 5000);Sourcepub fn implicit_conditional(&self) -> bool
pub fn implicit_conditional(&self) -> bool
Implicit conditional (equivalent to probability_exceeds(0.5))
This provides a convenient way to use uncertain booleans in if statements while still respecting the uncertainty.
§Example
use uncertain_rs::{Uncertain, operations::Comparison};
let measurement = Uncertain::normal(10.0, 2.0);
let above_threshold = Comparison::gt(&measurement, 8.0);
if above_threshold.implicit_conditional() {
println!("More likely than not above threshold");
}Sourcepub fn evaluate_hypothesis(
&self,
threshold: f64,
confidence_level: f64,
max_samples: usize,
epsilon: Option<f64>,
alpha: Option<f64>,
beta: Option<f64>,
batch_size: usize,
) -> HypothesisResult
pub fn evaluate_hypothesis( &self, threshold: f64, confidence_level: f64, max_samples: usize, epsilon: Option<f64>, alpha: Option<f64>, beta: Option<f64>, batch_size: usize, ) -> HypothesisResult
Performs Sequential Probability Ratio Test (SPRT) for efficient hypothesis testing
This implements the SPRT algorithm described in the paper for efficient evidence evaluation with automatic sample size determination.
§Arguments
threshold- Probability threshold for H1: P(true) > thresholdconfidence_level- Overall confidence levelmax_samples- Maximum samples before fallback decisionepsilon- Indifference region size (default: 0.05)alpha- Type I error rate (false positive, default: 1 -confidence_level)beta- Type II error rate (false negative, default: alpha)batch_size- Samples to process in each batch (default: 10)
§Returns
HypothesisResult containing the decision and test statistics
§Example
use uncertain_rs::Uncertain;
let biased_coin = Uncertain::bernoulli(0.7);
let result = biased_coin.evaluate_hypothesis(
0.6, // threshold
0.95, // confidence_level
5000, // max_samples
Some(0.05), // epsilon
Some(0.01), // alpha (Type I error)
Some(0.01), // beta (Type II error)
20, // batch_size
);
println!("Decision: {}", result.decision);
println!("Probability: {:.3}", result.probability);
println!("Samples used: {}", result.samples_used);Sourcepub fn estimate_probability(&self, sample_count: usize) -> f64
pub fn estimate_probability(&self, sample_count: usize) -> f64
Estimates the probability that this condition is true
§Example
use uncertain_rs::Uncertain;
let condition = Uncertain::bernoulli(0.7);
let prob = condition.estimate_probability(1000);
// Should be approximately 0.7Sourcepub fn bayesian_update(
prior_prob: f64,
evidence: &Uncertain<bool>,
likelihood_given_true: f64,
likelihood_given_false: f64,
sample_count: usize,
) -> f64
pub fn bayesian_update( prior_prob: f64, evidence: &Uncertain<bool>, likelihood_given_true: f64, likelihood_given_false: f64, sample_count: usize, ) -> f64
Bayesian evidence update using Bayes’ theorem
Updates the probability of this condition given observed evidence.
§Arguments
prior_prob- Prior probability of the conditionevidence- Observed evidence (another uncertain boolean)likelihood_given_true- P(evidence | condition is true)likelihood_given_false- P(evidence | condition is false)sample_count- Number of samples for estimation
§Example
use uncertain_rs::Uncertain;
let disease = Uncertain::bernoulli(0.01); // 1% base rate
let test_positive = Uncertain::bernoulli(0.95); // Test result
let posterior = Uncertain::bayesian_update(
0.01, // prior probability
&test_positive,
0.95, // sensitivity (true positive rate)
0.05, // false positive rate
1000
);Source§impl Uncertain<f64>
impl Uncertain<f64>
Sourcepub fn pow(&self, exponent: f64) -> Uncertain<f64>
pub fn pow(&self, exponent: f64) -> Uncertain<f64>
Raises the uncertain value to a power
§Example
use uncertain_rs::Uncertain;
let base = Uncertain::normal(2.0, 0.1);
let squared = base.pow(2.0);Sourcepub fn sqrt(&self) -> Uncertain<f64>
pub fn sqrt(&self) -> Uncertain<f64>
Takes the square root of the uncertain value
§Example
use uncertain_rs::Uncertain;
let positive = Uncertain::uniform(1.0, 100.0);
let sqrt_val = positive.sqrt();Sourcepub fn ln(&self) -> Uncertain<f64>
pub fn ln(&self) -> Uncertain<f64>
Takes the natural logarithm of the uncertain value
§Example
use uncertain_rs::Uncertain;
let positive = Uncertain::uniform(0.1, 10.0);
let ln_val = positive.ln();Sourcepub fn exp(&self) -> Uncertain<f64>
pub fn exp(&self) -> Uncertain<f64>
Takes the exponential of the uncertain value
§Example
use uncertain_rs::Uncertain;
let normal = Uncertain::normal(0.0, 1.0);
let exp_val = normal.exp();Source§impl<T> Uncertain<T>
impl<T> Uncertain<T>
Sourcepub fn gt_uncertain(&self, other: &Self) -> Uncertain<bool>
pub fn gt_uncertain(&self, other: &Self) -> Uncertain<bool>
Compare two uncertain values for greater than
§Example
use uncertain_rs::Uncertain;
let sensor1 = Uncertain::normal(10.0, 1.0);
let sensor2 = Uncertain::normal(12.0, 1.0);
let evidence = sensor2.gt_uncertain(&sensor1);Sourcepub fn lt_uncertain(&self, other: &Self) -> Uncertain<bool>
pub fn lt_uncertain(&self, other: &Self) -> Uncertain<bool>
Compare two uncertain values for less than
Sourcepub fn eq_uncertain(&self, other: &Self) -> Uncertain<bool>
pub fn eq_uncertain(&self, other: &Self) -> Uncertain<bool>
Compare two uncertain values for equality
Source§impl Uncertain<f64>
impl Uncertain<f64>
Sourcepub fn approx_eq(&self, target: f64, tolerance: f64) -> Uncertain<bool>
pub fn approx_eq(&self, target: f64, tolerance: f64) -> Uncertain<bool>
Check if value is approximately equal within tolerance
§Example
use uncertain_rs::Uncertain;
let measurement = Uncertain::normal(10.0, 0.1);
let target = 10.0;
let tolerance = 0.5;
let close_evidence = measurement.approx_eq(target, tolerance);Source§impl Uncertain<bool>
impl Uncertain<bool>
Sourcepub fn if_then_else<T, F1, F2>(&self, if_true: F1, if_false: F2) -> Uncertain<T>
pub fn if_then_else<T, F1, F2>(&self, if_true: F1, if_false: F2) -> Uncertain<T>
Conditional logic: if-then-else for uncertain booleans
§Example
use uncertain_rs::Uncertain;
let condition = Uncertain::bernoulli(0.7);
let result = condition.if_then_else(
|| Uncertain::point(10.0),
|| Uncertain::point(5.0)
);Sourcepub fn implies(&self, consequent: &Self) -> Uncertain<bool>
pub fn implies(&self, consequent: &Self) -> Uncertain<bool>
Implication: if A then B (equivalent to !A || B)
§Example
use uncertain_rs::Uncertain;
let raining = Uncertain::bernoulli(0.3);
let umbrella = Uncertain::bernoulli(0.8);
// If it's raining, then I should have an umbrella
let implication = raining.implies(&umbrella);Sourcepub fn if_and_only_if(&self, other: &Self) -> Uncertain<bool>
pub fn if_and_only_if(&self, other: &Self) -> Uncertain<bool>
Bi-conditional: A if and only if B (equivalent to (A && B) || (!A && !B))
Sourcepub fn probability(&self, sample_count: usize) -> f64
pub fn probability(&self, sample_count: usize) -> f64
Probability that this condition is true
§Example
use uncertain_rs::Uncertain;
let condition = Uncertain::bernoulli(0.7);
let prob = condition.probability(1000);
// Should be approximately 0.7Source§impl<T> Uncertain<T>where
T: Shareable,
Statistical analysis methods for uncertain values
impl<T> Uncertain<T>where
T: Shareable,
Statistical analysis methods for uncertain values
Sourcepub fn mode(&self, sample_count: usize) -> Option<T>
pub fn mode(&self, sample_count: usize) -> Option<T>
Estimates the mode (most frequent value) of the distribution
§Example
use uncertain_rs::Uncertain;
use std::collections::HashMap;
let mut probs = HashMap::new();
probs.insert("red", 0.5);
probs.insert("blue", 0.3);
probs.insert("green", 0.2);
let categorical = Uncertain::categorical(&probs).unwrap();
let mode = categorical.mode(1000);
// Should likely be "red"Sourcepub fn histogram(&self, sample_count: usize) -> HashMap<T, usize>
pub fn histogram(&self, sample_count: usize) -> HashMap<T, usize>
Creates a histogram of the distribution
§Example
use uncertain_rs::Uncertain;
let bernoulli = Uncertain::bernoulli(0.7);
let histogram = bernoulli.histogram(1000);
// Should show roughly 700 true, 300 falseSource§impl<T> Uncertain<T>
Lazy evaluation methods for statistical operations
impl<T> Uncertain<T>
Lazy evaluation methods for statistical operations
Sourcepub fn lazy_stats(&self, sample_count: usize) -> LazyStats<T>
pub fn lazy_stats(&self, sample_count: usize) -> LazyStats<T>
Create a lazy statistics wrapper that defers expensive computations until they are actually needed and reuses intermediate results
Recommended usage: When you need multiple statistics from the same distribution,
use this method to get a LazyStats object and call multiple methods on it.
This provides maximum performance by reusing samples and intermediate computations.
§Example
use uncertain_rs::Uncertain;
let normal = Uncertain::normal(10.0, 2.0);
let stats = normal.lazy_stats(1000);
// All of these reuse the same 1000 samples:
let mean = stats.mean(); // Computes samples once
let variance = stats.variance(); // Reuses samples and mean
let std_dev = stats.std_dev(); // Reuses variance
let median = stats.quantile(0.5); // Reuses sorted samples
let (lo, hi) = stats.confidence_interval(0.95); // Reuses sorted samples
// This is much more efficient than calling individual methods:
// normal.expected_value(1000), normal.variance(1000), etc.Sourcepub fn stats(&self, sample_count: usize) -> LazyStats<T>
pub fn stats(&self, sample_count: usize) -> LazyStats<T>
Get statistics using lazy evaluation (alias for lazy_stats)
This is provided as a more concise alias for users who prefer shorter method names.
Sourcepub fn progressive_stats() -> ProgressiveStats
pub fn progressive_stats() -> ProgressiveStats
Create a progressive statistics accumulator that builds results incrementally This is useful when you want to analyze samples as they are generated
§Example
use uncertain_rs::Uncertain;
let normal = Uncertain::normal(5.0, 1.0);
let mut progressive = Uncertain::<f64>::progressive_stats();
// Add samples incrementally
for _ in 0..1000 {
progressive.add_sample(normal.sample());
}
let mean = progressive.mean();
let variance = progressive.variance();Sourcepub fn compute_stats_batch(&self, sample_count: usize) -> ProgressiveStats
pub fn compute_stats_batch(&self, sample_count: usize) -> ProgressiveStats
Compute multiple statistics lazily with a single sample generation pass This is more efficient than calling individual methods when you need multiple stats
§Example
use uncertain_rs::Uncertain;
let normal = Uncertain::normal(0.0, 1.0);
let stats = normal.compute_stats_batch(1000);
println!("Mean: {}, Std Dev: {}, Range: {}",
stats.mean(), stats.std_dev(), stats.range());Source§impl<T> Uncertain<T>
Statistical methods for numeric types
impl<T> Uncertain<T>
Statistical methods for numeric types
Sourcepub fn expected_value(&self, sample_count: usize) -> f64
pub fn expected_value(&self, sample_count: usize) -> f64
Calculates the expected value (mean) of the distribution
Note: For multiple statistical operations on the same distribution,
use lazy_stats() to get a LazyStats object for optimal performance
with sample reuse and caching.
§Example
use uncertain_rs::Uncertain;
let normal = Uncertain::normal(10.0, 2.0);
let mean = normal.expected_value(1000);
// Should be approximately 10.0
// For multiple stats, use lazy_stats for better performance:
let stats = normal.lazy_stats(1000);
let mean = stats.mean();
let variance = stats.variance(); // Reuses same samplesSourcepub fn expected_value_adaptive(&self, config: &AdaptiveSampling) -> f64
pub fn expected_value_adaptive(&self, config: &AdaptiveSampling) -> f64
Calculates the expected value using adaptive sampling for better efficiency
This method automatically determines the optimal sample count based on convergence criteria, potentially improving cache hit rates for similar computations.
§Example
use uncertain_rs::Uncertain;
use uncertain_rs::computation::AdaptiveSampling;
let normal = Uncertain::normal(10.0, 2.0);
let config = AdaptiveSampling::default();
let mean = normal.expected_value_adaptive(&config);
// Should be approximately 10.0 with optimal sample countSourcepub fn adaptive_lazy_stats(
&self,
config: &AdaptiveSampling,
) -> AdaptiveLazyStats<T>
pub fn adaptive_lazy_stats( &self, config: &AdaptiveSampling, ) -> AdaptiveLazyStats<T>
Adaptive lazy statistical computation that progressively adds samples until convergence This provides optimal performance by only computing as many samples as needed
§Example
use uncertain_rs::Uncertain;
use uncertain_rs::computation::AdaptiveSampling;
let normal = Uncertain::normal(10.0, 2.0);
let config = AdaptiveSampling::default();
let lazy_stats = normal.adaptive_lazy_stats(&config);
// Automatically uses optimal sample count for each statistic
let mean = lazy_stats.mean();
let std_dev = lazy_stats.std_dev();Sourcepub fn variance(&self, sample_count: usize) -> f64
pub fn variance(&self, sample_count: usize) -> f64
Calculates the variance of the distribution
Note: For multiple statistical operations on the same distribution,
use lazy_stats() to get a LazyStats object for optimal performance
with sample reuse and caching.
§Example
use uncertain_rs::Uncertain;
let normal = Uncertain::normal(0.0, 2.0);
let variance = normal.variance(1000);
// Should be approximately 4.0 (std_dev^2)
// For multiple stats, use lazy_stats for better performance:
let stats = normal.lazy_stats(1000);
let variance = stats.variance();
let std_dev = stats.std_dev(); // Reuses variance calculationSourcepub fn standard_deviation(&self, sample_count: usize) -> f64
pub fn standard_deviation(&self, sample_count: usize) -> f64
Calculates the standard deviation of the distribution
Note: For multiple statistical operations on the same distribution,
use lazy_stats() to get a LazyStats object for optimal performance
with sample reuse and caching.
§Example
use uncertain_rs::Uncertain;
let normal = Uncertain::normal(0.0, 2.0);
let std_dev = normal.standard_deviation(1000);
// Should be approximately 2.0
// For multiple stats, use lazy_stats for better performance:
let stats = normal.lazy_stats(1000);
let std_dev = stats.std_dev();
let variance = stats.variance(); // Reuses same samplesSourcepub fn skewness(&self, sample_count: usize) -> f64
pub fn skewness(&self, sample_count: usize) -> f64
Calculates the skewness of the distribution
This method uses caching to avoid recomputing the same result.
§Example
use uncertain_rs::Uncertain;
let normal = Uncertain::normal(0.0, 1.0);
let skewness = normal.skewness(1000);
// Should be approximately 0 for normal distributionSourcepub fn kurtosis(&self, sample_count: usize) -> f64
pub fn kurtosis(&self, sample_count: usize) -> f64
Calculates the excess kurtosis of the distribution
This method uses caching to avoid recomputing the same result.
§Example
use uncertain_rs::Uncertain;
let normal = Uncertain::normal(0.0, 1.0);
let kurtosis = normal.kurtosis(1000);
// Should be approximately 0 for normal distribution (excess kurtosis)Source§impl<T> Uncertain<T>
Statistical methods for ordered types
impl<T> Uncertain<T>
Statistical methods for ordered types
Sourcepub fn confidence_interval(
&self,
confidence: f64,
sample_count: usize,
) -> (f64, f64)
pub fn confidence_interval( &self, confidence: f64, sample_count: usize, ) -> (f64, f64)
Calculates confidence interval bounds
Note: For multiple statistical operations on the same distribution,
use lazy_stats() to get a LazyStats object for optimal performance
with sample reuse and caching.
§Example
use uncertain_rs::Uncertain;
let normal = Uncertain::normal(100.0, 15.0);
let (lower, upper) = normal.confidence_interval(0.95, 1000);
// 95% of values should fall between lower and upper
// For multiple stats, use lazy_stats for better performance:
let stats = normal.lazy_stats(1000);
let (lower, upper) = stats.confidence_interval(0.95);
let median = stats.quantile(0.5); // Reuses sorted samplesSourcepub fn cdf(&self, value: f64, sample_count: usize) -> f64
pub fn cdf(&self, value: f64, sample_count: usize) -> f64
Estimates the cumulative distribution function (CDF) at a given value
This method uses caching to avoid recomputing the same result.
§Example
use uncertain_rs::Uncertain;
let normal = Uncertain::normal(0.0, 1.0);
let prob = normal.cdf(0.0, 1000);
// Should be approximately 0.5 for standard normal at 0Sourcepub fn quantile(&self, q: f64, sample_count: usize) -> f64
pub fn quantile(&self, q: f64, sample_count: usize) -> f64
Estimates quantiles of the distribution using linear interpolation
Note: For multiple statistical operations on the same distribution,
use lazy_stats() to get a LazyStats object for optimal performance
with sample reuse and caching.
§Example
use uncertain_rs::Uncertain;
let normal = Uncertain::normal(0.0, 1.0);
let median = normal.quantile(0.5, 1000);
// Should be approximately 0.0 for standard normal
// For multiple quantiles, use lazy_stats for better performance:
let stats = normal.lazy_stats(1000);
let q25 = stats.quantile(0.25);
let q75 = stats.quantile(0.75); // Reuses sorted samplesSourcepub fn interquartile_range(&self, sample_count: usize) -> f64
pub fn interquartile_range(&self, sample_count: usize) -> f64
Calculates the interquartile range (IQR)
§Example
use uncertain_rs::Uncertain;
let normal = Uncertain::normal(0.0, 1.0);
let iqr = normal.interquartile_range(1000);
// IQR for standard normal is approximately 1.35Sourcepub fn median_absolute_deviation(&self, sample_count: usize) -> f64
pub fn median_absolute_deviation(&self, sample_count: usize) -> f64
Source§impl Uncertain<f64>
Advanced statistical methods
impl Uncertain<f64>
Advanced statistical methods
Sourcepub fn pdf_kde(&self, x: f64, sample_count: usize, bandwidth: f64) -> f64
pub fn pdf_kde(&self, x: f64, sample_count: usize, bandwidth: f64) -> f64
Estimates the probability density function (PDF) using kernel density estimation
This method uses caching to avoid recomputing the same result.
§Example
use uncertain_rs::Uncertain;
let normal = Uncertain::normal(0.0, 1.0);
let density = normal.pdf_kde(0.0, 1000, 0.1);Sourcepub fn log_likelihood(&self, x: f64, sample_count: usize, bandwidth: f64) -> f64
pub fn log_likelihood(&self, x: f64, sample_count: usize, bandwidth: f64) -> f64
Estimates the log-likelihood of a value using kernel density estimation
§Example
use uncertain_rs::Uncertain;
let normal = Uncertain::normal(0.0, 1.0);
let log_likelihood = normal.log_likelihood(0.0, 1000, 0.1);Sourcepub fn correlation(&self, other: &Uncertain<f64>, sample_count: usize) -> f64
pub fn correlation(&self, other: &Uncertain<f64>, sample_count: usize) -> f64
Estimates correlation with another uncertain value
§Example
use uncertain_rs::Uncertain;
let x = Uncertain::normal(0.0, 1.0);
let y = x.map(|v| v * 2.0 + Uncertain::normal(0.0, 0.5).sample());
let correlation = x.correlation(&y, 1000);
// Should be positive correlationSource§impl<T> Uncertain<T>where
T: Shareable,
impl<T> Uncertain<T>where
T: Shareable,
Sourcepub fn new<F>(sampler: F) -> Self
pub fn new<F>(sampler: F) -> Self
Creates an uncertain value with the given sampling function.
§Example
use uncertain_rs::Uncertain;
let custom = Uncertain::new(|| {
// Your custom sampling logic
rand::random::<f64>() * 10.0
});Sourcepub fn id(&self) -> Uuid
pub fn id(&self) -> Uuid
Get the unique identifier for this uncertain value
This is primarily used for caching purposes.
Sourcepub fn sample(&self) -> T
pub fn sample(&self) -> T
Generate a sample from this distribution
§Example
use uncertain_rs::Uncertain;
let normal = Uncertain::normal(0.0, 1.0);
let sample = normal.sample();
println!("Sample: {}", sample);Sourcepub fn map<U, F>(&self, transform: F) -> Uncertain<U>
pub fn map<U, F>(&self, transform: F) -> Uncertain<U>
Transforms an uncertain value by applying a function to each sample.
§Example
use uncertain_rs::Uncertain;
let celsius = Uncertain::normal(20.0, 2.0);
let fahrenheit = celsius.map(|c| c * 9.0/5.0 + 32.0);Sourcepub fn flat_map<U, F>(&self, transform: F) -> Uncertain<U>
pub fn flat_map<U, F>(&self, transform: F) -> Uncertain<U>
Transforms an uncertain value by applying a function that returns another uncertain value.
§Example
use uncertain_rs::Uncertain;
let base = Uncertain::normal(5.0, 1.0);
let dependent = base.flat_map(|b| Uncertain::normal(b, 0.5));Sourcepub fn filter<F>(&self, predicate: F) -> Uncertain<T>
pub fn filter<F>(&self, predicate: F) -> Uncertain<T>
Filters samples using rejection sampling.
Only samples that satisfy the predicate are accepted. This method will keep sampling until a valid sample is found, so ensure the predicate has a reasonable acceptance rate.
§Example
use uncertain_rs::Uncertain;
let normal = Uncertain::normal(0.0, 1.0);
let positive_only = normal.filter(|&x| x > 0.0);Sourcepub fn samples(&self) -> impl Iterator<Item = T> + '_
pub fn samples(&self) -> impl Iterator<Item = T> + '_
Generate an iterator of samples
§Example
use uncertain_rs::Uncertain;
let normal = Uncertain::normal(0.0, 1.0);
let first_10: Vec<f64> = normal.samples().take(10).collect();Sourcepub fn take_samples(&self, count: usize) -> Vec<T>
pub fn take_samples(&self, count: usize) -> Vec<T>
Take a specific number of samples
§Example
use uncertain_rs::Uncertain;
let uniform = Uncertain::uniform(0.0, 1.0);
let samples = uniform.take_samples(1000);Source§impl Uncertain<f64>
impl Uncertain<f64>
Sourcepub fn take_samples_cached(&self, count: usize) -> Vec<f64>
pub fn take_samples_cached(&self, count: usize) -> Vec<f64>
Take samples with caching for better performance on repeated requests
This is especially useful for expensive computations that might be called multiple times with the same sample count.
§Example
use uncertain_rs::Uncertain;
let gamma = Uncertain::gamma(2.0, 1.0);
let samples = gamma.take_samples_cached(1000); // Cached for reuseSource§impl<T> Uncertain<T>where
T: Shareable + PartialOrd,
impl<T> Uncertain<T>where
T: Shareable + PartialOrd,
Source§impl<T> Uncertain<T>
impl<T> Uncertain<T>
Sourcepub fn gt(&self, threshold: T) -> Uncertain<bool>
pub fn gt(&self, threshold: T) -> Uncertain<bool>
Returns uncertain boolean evidence that this value is greater than threshold
§Example
use uncertain_rs::Uncertain;
let speed = Uncertain::normal(55.2, 5.0);
let speeding_evidence = speed.gt(60.0);
if speeding_evidence.probability_exceeds(0.95) {
println!("Issue speeding ticket");
}Sourcepub fn lt(&self, threshold: T) -> Uncertain<bool>
pub fn lt(&self, threshold: T) -> Uncertain<bool>
Returns uncertain boolean evidence that this value is less than threshold
Sourcepub fn ge(&self, threshold: T) -> Uncertain<bool>
pub fn ge(&self, threshold: T) -> Uncertain<bool>
Returns uncertain boolean evidence that this value is greater than or equal to threshold
Sourcepub fn le(&self, threshold: T) -> Uncertain<bool>
pub fn le(&self, threshold: T) -> Uncertain<bool>
Returns uncertain boolean evidence that this value is less than or equal to threshold
Trait Implementations§
Source§impl<T> Add<T> for Uncertain<T>where
T: Arithmetic,
impl<T> Add<T> for Uncertain<T>where
T: Arithmetic,
Source§impl<T> Add for Uncertain<T>where
T: Arithmetic,
impl<T> Add for Uncertain<T>where
T: Arithmetic,
Source§impl<T> Comparison<T> for Uncertain<T>
impl<T> Comparison<T> for Uncertain<T>
Source§fn gt(&self, threshold: T) -> Uncertain<bool>
fn gt(&self, threshold: T) -> Uncertain<bool>
Greater than comparison
§Example
use uncertain_rs::Uncertain;
let speed = Uncertain::normal(55.0, 5.0);
let speeding_evidence = speed.gt(60.0);
if speeding_evidence.probability_exceeds(0.95) {
println!("95% confident speeding");
}Source§fn lt(&self, threshold: T) -> Uncertain<bool>
fn lt(&self, threshold: T) -> Uncertain<bool>
Less than comparison
§Example
use uncertain_rs::Uncertain;
let temperature = Uncertain::normal(1.0, 2.0);
let freezing_evidence = temperature.lt(0.0);
if freezing_evidence.probability_exceeds(0.8) {
println!("Likely freezing");
}Source§impl<T> Div<T> for Uncertain<T>where
T: Arithmetic,
impl<T> Div<T> for Uncertain<T>where
T: Arithmetic,
Source§impl<T> Div for Uncertain<T>where
T: Arithmetic,
impl<T> Div for Uncertain<T>where
T: Arithmetic,
Source§impl LogicalOps for Uncertain<bool>
impl LogicalOps for Uncertain<bool>
Source§fn and(&self, other: &Self) -> Self
fn and(&self, other: &Self) -> Self
Logical AND: both conditions must be true
§Example
use uncertain_rs::{Uncertain, operations::LogicalOps};
let temp = Uncertain::normal(20.0, 2.0);
let humidity = Uncertain::normal(50.0, 5.0);
let temp_ok = temp.ge(18.0).and(&temp.le(25.0));
let humidity_ok = humidity.ge(40.0).and(&humidity.le(60.0));
let comfortable = temp_ok.and(&humidity_ok);
if comfortable.probability_exceeds(0.8) {
println!("Environment is comfortable");
}Source§fn or(&self, other: &Self) -> Self
fn or(&self, other: &Self) -> Self
Logical OR: at least one condition must be true
§Example
use uncertain_rs::{Uncertain, operations::{LogicalOps, Comparison}};
let temperature = Uncertain::normal(25.0, 5.0);
let high_temp = Comparison::gt(&temperature, 30.0);
let humidity = Uncertain::normal(75.0, 10.0);
let high_humidity = Comparison::gt(&humidity, 80.0);
let uncomfortable = LogicalOps::or(&high_temp, &high_humidity);