Uncertain

Struct Uncertain 

Source
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,

Source

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);
Source

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 mix
  • weights - 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();
Source

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>
where T: Clone + Send + Sync + Hash + Eq + 'static,

Source

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>

Source

pub fn normal(mean: f64, std_dev: f64) -> Self

Creates a normal (Gaussian) distribution

§Arguments
  • mean - The mean of the distribution
  • std_dev - The standard deviation
§Example
use uncertain_rs::Uncertain;

let normal = Uncertain::normal(0.0, 1.0); // Standard normal
let measurement = Uncertain::normal(100.0, 5.0); // Measurement with error
Source

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);
Source

pub fn exponential(rate: f64) -> Self

Creates an exponential distribution

§Arguments
  • rate - The rate parameter (lambda)
§Example
use uncertain_rs::Uncertain;

let exponential = Uncertain::exponential(1.0);
Source

pub fn log_normal(mu: f64, sigma: f64) -> Self

Creates a log-normal distribution

§Arguments
  • mu - Mean of the underlying normal distribution
  • sigma - Standard deviation of the underlying normal distribution
§Example
use uncertain_rs::Uncertain;

let lognormal = Uncertain::log_normal(0.0, 1.0);
Source

pub fn beta(alpha: f64, beta: f64) -> Self

Creates a beta distribution

§Arguments
  • alpha - First shape parameter
  • beta - Second shape parameter
§Example
use uncertain_rs::Uncertain;

let beta = Uncertain::beta(2.0, 5.0);
Source

pub fn gamma(shape: f64, scale: f64) -> Self

Creates a gamma distribution

§Arguments
  • shape - Shape parameter (alpha)
  • scale - Scale parameter (beta)
§Example
use uncertain_rs::Uncertain;

let gamma = Uncertain::gamma(2.0, 1.0);
Source§

impl Uncertain<bool>

Source

pub fn bernoulli(probability: f64) -> Self

Creates a Bernoulli distribution

§Arguments
  • probability - Probability of success (true)
§Example
use uncertain_rs::Uncertain;

let biased_coin = Uncertain::bernoulli(0.7); // 70% chance of true
Source§

impl<T> Uncertain<T>
where T: Clone + Send + Sync + From<u32> + AddAssign + Sub<Output = T> + Default + 'static,

Source

pub fn binomial(trials: u32, probability: f64) -> Self

Creates a binomial distribution

§Arguments
  • trials - Number of trials
  • probability - Probability of success on each trial
§Example
use uncertain_rs::Uncertain;

let binomial: Uncertain<u32> = Uncertain::binomial(100, 0.3);
Source

pub fn poisson(lambda: f64) -> Self

Creates a Poisson distribution

§Arguments
  • lambda - Rate parameter
§Example
use uncertain_rs::Uncertain;

let poisson: Uncertain<u32> = Uncertain::poisson(3.5);
Source

pub fn geometric(probability: f64) -> Self

Creates a geometric distribution

§Arguments
  • probability - Probability of success on each trial
§Example
use uncertain_rs::Uncertain;

let geometric: Uncertain<u32> = Uncertain::geometric(0.1);
Source§

impl Uncertain<bool>

Evidence-based conditional methods for uncertain boolean values

Source

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 exceed
  • confidence_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");
}
Source

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);
Source

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");
}
Source

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) > threshold
  • confidence_level - Overall confidence level
  • max_samples - Maximum samples before fallback decision
  • epsilon - 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);
Source

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.7
Source

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 condition
  • evidence - 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>

Source

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);
Source

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();
Source

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();
Source

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

pub fn abs(&self) -> Uncertain<f64>

Takes the absolute value of the uncertain value

§Example
use uncertain_rs::Uncertain;

let normal = Uncertain::normal(0.0, 2.0);
let abs_val = normal.abs();
Source

pub fn sin(&self) -> Uncertain<f64>

Applies sine function to the uncertain value

Source

pub fn cos(&self) -> Uncertain<f64>

Applies cosine function to the uncertain value

Source

pub fn tan(&self) -> Uncertain<f64>

Applies tangent function to the uncertain value

Source§

impl<T> Uncertain<T>

Source

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);
Source

pub fn lt_uncertain(&self, other: &Self) -> Uncertain<bool>

Compare two uncertain values for less than

Source

pub fn eq_uncertain(&self, other: &Self) -> Uncertain<bool>

Compare two uncertain values for equality

Source§

impl Uncertain<f64>

Source

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

pub fn within_range(&self, min: f64, max: f64) -> Uncertain<bool>

Check if value is within a range

§Example
use uncertain_rs::Uncertain;

let measurement = Uncertain::normal(10.0, 2.0);
let in_range = measurement.within_range(8.0, 12.0);
Source§

impl Uncertain<bool>

Source

pub fn if_then_else<T, F1, F2>(&self, if_true: F1, if_false: F2) -> Uncertain<T>
where T: Shareable, F1: Fn() -> Uncertain<T> + Send + Sync + 'static, F2: Fn() -> Uncertain<T> + Send + Sync + 'static,

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)
);
Source

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);
Source

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))

Source

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.7
Source§

impl<T> Uncertain<T>
where T: Shareable,

Statistical analysis methods for uncertain values

Source

pub fn mode(&self, sample_count: usize) -> Option<T>
where T: Hash + Eq,

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"
Source

pub fn histogram(&self, sample_count: usize) -> HashMap<T, usize>
where T: Hash + Eq,

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 false
Source

pub fn entropy(&self, sample_count: usize) -> f64
where T: Hash + Eq,

Calculates the empirical entropy of the distribution in bits

§Example
use uncertain_rs::Uncertain;

let uniform_coin = Uncertain::bernoulli(0.5);
let entropy = uniform_coin.entropy(1000);
// Should be close to 1.0 bit for fair coin
Source§

impl<T> Uncertain<T>
where T: Shareable + Into<f64> + Clone,

Lazy evaluation methods for statistical operations

Source

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.
Source

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.

Source

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();
Source

pub fn compute_stats_batch(&self, sample_count: usize) -> ProgressiveStats
where T: Into<f64>,

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>
where T: Clone + Send + Sync + Into<f64> + 'static,

Statistical methods for numeric types

Source

pub fn expected_value(&self, sample_count: usize) -> f64
where T: Into<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 samples
Source

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 count
Source

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();
Source

pub fn variance(&self, sample_count: usize) -> f64
where T: Into<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 calculation
Source

pub fn standard_deviation(&self, sample_count: usize) -> f64
where T: Into<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 samples
Source

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 distribution
Source

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>
where T: Clone + Send + Sync + PartialOrd + Into<f64> + 'static,

Statistical methods for ordered types

Source

pub fn confidence_interval( &self, confidence: f64, sample_count: usize, ) -> (f64, f64)
where T: Into<f64> + PartialOrd,

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 samples
Source

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 0
Source

pub fn quantile(&self, q: f64, sample_count: usize) -> f64
where T: Into<f64> + PartialOrd,

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 samples
Source

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.35
Source

pub fn median_absolute_deviation(&self, sample_count: usize) -> f64

Estimates the median absolute deviation (MAD)

§Panics

Panics if the samples contain values that cannot be compared (e.g., NaN values).

§Example
use uncertain_rs::Uncertain;

let normal = Uncertain::normal(0.0, 1.0);
let mad = normal.median_absolute_deviation(1000);
Source§

impl Uncertain<f64>

Advanced statistical methods

Source

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);
Source

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);
Source

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 correlation
Source§

impl<T> Uncertain<T>
where T: Shareable,

Source

pub fn new<F>(sampler: F) -> Self
where F: Fn() -> T + Send + Sync + 'static,

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
});
Source

pub fn id(&self) -> Uuid

Get the unique identifier for this uncertain value

This is primarily used for caching purposes.

Source

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);
Source

pub fn map<U, F>(&self, transform: F) -> Uncertain<U>
where U: Shareable, F: Fn(T) -> U + Send + Sync + 'static,

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);
Source

pub fn flat_map<U, F>(&self, transform: F) -> Uncertain<U>
where U: Shareable, F: Fn(T) -> Uncertain<U> + Send + Sync + 'static,

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));
Source

pub fn filter<F>(&self, predicate: F) -> Uncertain<T>
where F: Fn(&T) -> bool + Send + Sync + 'static,

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);
Source

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();
Source

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>

Source

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 reuse
Source§

impl<T> Uncertain<T>
where T: Shareable + PartialOrd,

Source

pub fn less_than(&self, other: &Self) -> Uncertain<bool>

Compare this uncertain value with another, returning an uncertain boolean

Source

pub fn greater_than(&self, other: &Self) -> Uncertain<bool>

Compare this uncertain value with another, returning an uncertain boolean

Source§

impl<T> Uncertain<T>

Source

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");
}
Source

pub fn lt(&self, threshold: T) -> Uncertain<bool>

Returns uncertain boolean evidence that this value is less than threshold

Source

pub fn ge(&self, threshold: T) -> Uncertain<bool>

Returns uncertain boolean evidence that this value is greater than or equal to threshold

Source

pub fn le(&self, threshold: T) -> Uncertain<bool>

Returns uncertain boolean evidence that this value is less than or equal to threshold

Source

pub fn eq_value(&self, threshold: T) -> Uncertain<bool>

Returns uncertain boolean evidence that this value equals threshold

Note: For floating point types, exact equality is rarely meaningful. Consider using range-based comparisons instead.

Source

pub fn ne_value(&self, threshold: T) -> Uncertain<bool>

Returns uncertain boolean evidence that this value does not equal threshold

Trait Implementations§

Source§

impl<T> Add<T> for Uncertain<T>
where T: Arithmetic,

Source§

type Output = Uncertain<T>

The resulting type after applying the + operator.
Source§

fn add(self, rhs: T) -> Self::Output

Performs the + operation. Read more
Source§

impl Add<Uncertain<f64>> for f64

Source§

type Output = Uncertain<f64>

The resulting type after applying the + operator.
Source§

fn add(self, rhs: Uncertain<f64>) -> Self::Output

Performs the + operation. Read more
Source§

impl<T> Add for Uncertain<T>
where T: Arithmetic,

Source§

type Output = Uncertain<T>

The resulting type after applying the + operator.
Source§

fn add(self, rhs: Self) -> Self::Output

Performs the + operation. Read more
Source§

impl BitAnd for Uncertain<bool>

Source§

type Output = Uncertain<bool>

The resulting type after applying the & operator.
Source§

fn bitand(self, rhs: Self) -> Self::Output

Performs the & operation. Read more
Source§

impl BitOr for Uncertain<bool>

Source§

type Output = Uncertain<bool>

The resulting type after applying the | operator.
Source§

fn bitor(self, rhs: Self) -> Self::Output

Performs the | operation. Read more
Source§

impl<T: Clone> Clone for Uncertain<T>

Source§

fn clone(&self) -> Uncertain<T>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T> Comparison<T> for Uncertain<T>

Source§

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>

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§

fn ge(&self, threshold: T) -> Uncertain<bool>

Greater than or equal comparison

Source§

fn le(&self, threshold: T) -> Uncertain<bool>

Less than or equal comparison

Source§

fn eq(&self, threshold: T) -> Uncertain<bool>

Equality comparison

Note: For floating point types, exact equality is rarely meaningful. Consider using range-based comparisons instead.

Source§

fn ne(&self, threshold: T) -> Uncertain<bool>

Inequality comparison

Source§

impl<T> Debug for Uncertain<T>
where T: Shareable + Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T> Div<T> for Uncertain<T>
where T: Arithmetic,

Source§

type Output = Uncertain<T>

The resulting type after applying the / operator.
Source§

fn div(self, rhs: T) -> Self::Output

Performs the / operation. Read more
Source§

impl Div<Uncertain<f64>> for f64

Source§

type Output = Uncertain<f64>

The resulting type after applying the / operator.
Source§

fn div(self, rhs: Uncertain<f64>) -> Self::Output

Performs the / operation. Read more
Source§

impl<T> Div for Uncertain<T>
where T: Arithmetic,

Source§

type Output = Uncertain<T>

The resulting type after applying the / operator.
Source§

fn div(self, rhs: Self) -> Self::Output

Performs the / operation. Read more
Source§

impl LogicalOps for Uncertain<bool>

Source§

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

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);
Source§

fn not(&self) -> Self

Logical NOT: negation of the condition

§Example
use uncertain_rs::{Uncertain, operations::{LogicalOps, Comparison}};

let speed = Uncertain::normal(55.0, 5.0);
let speeding = Comparison::gt(&speed, 60.0);
let not_speeding = LogicalOps::not(&speeding);
Source§

fn xor(&self, other: &Self) -> Self

Logical XOR: exactly one condition must be true

Source§

fn nand(&self, other: &Self) -> Self

Logical NAND: NOT (both conditions true)

Source§

fn nor(&self, other: &Self) -> Self

Logical NOR: NOT (either condition true)

Source§

impl<T> Mul<T> for Uncertain<T>
where T: Arithmetic,

Source§

type Output = Uncertain<T>

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: T) -> Self::Output

Performs the * operation. Read more
Source§

impl Mul<Uncertain<f64>> for f64

Source§

type Output = Uncertain<f64>

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: Uncertain<f64>) -> Self::Output

Performs the * operation. Read more
Source§

impl<T> Mul for Uncertain<T>
where T: Arithmetic,

Source§

type Output = Uncertain<T>

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: Self) -> Self::Output

Performs the * operation. Read more
Source§

impl<T> Neg for Uncertain<T>
where T: Neg<Output = T> + Shareable,

Source§

type Output = Uncertain<T>

The resulting type after applying the - operator.
Source§

fn neg(self) -> Self::Output

Performs the unary - operation. Read more
Source§

impl Not for Uncertain<bool>

Source§

type Output = Uncertain<bool>

The resulting type after applying the ! operator.
Source§

fn not(self) -> Self::Output

Performs the unary ! operation. Read more
Source§

impl<T> PartialEq for Uncertain<T>
where T: Shareable + PartialEq,

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T> PartialOrd for Uncertain<T>
where T: Shareable + PartialOrd,

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
Source§

fn lt(&self, other: &Self) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
Source§

fn gt(&self, other: &Self) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<T> Sub<T> for Uncertain<T>
where T: Arithmetic,

Source§

type Output = Uncertain<T>

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: T) -> Self::Output

Performs the - operation. Read more
Source§

impl Sub<Uncertain<f64>> for f64

Source§

type Output = Uncertain<f64>

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: Uncertain<f64>) -> Self::Output

Performs the - operation. Read more
Source§

impl<T> Sub for Uncertain<T>
where T: Arithmetic,

Source§

type Output = Uncertain<T>

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: Self) -> Self::Output

Performs the - operation. Read more

Auto Trait Implementations§

§

impl<T> Freeze for Uncertain<T>

§

impl<T> !RefUnwindSafe for Uncertain<T>

§

impl<T> Send for Uncertain<T>

§

impl<T> Sync for Uncertain<T>

§

impl<T> Unpin for Uncertain<T>

§

impl<T> !UnwindSafe for Uncertain<T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> Shareable for T
where T: Clone + Send + Sync + 'static,