use crate::errors::stats_error::StatsError;
use deep_causality_algebra::RealField;
use deep_causality_num::FromPrimitive;
pub fn bernoulli_standard_error<T>(proportion: T, trials: u64) -> Result<T, StatsError>
where
T: RealField + FromPrimitive,
{
if !proportion.is_finite() {
return Err(StatsError::NonFiniteInput(
"a non-finite proportion has no sampling error",
));
}
if proportion < T::zero() || proportion > T::one() {
return Err(StatsError::NegativeProbability(
"a Bernoulli proportion lies in [0, 1]: outside it, p(1 − p) is negative and its \
square root is not real",
));
}
if trials == 0 {
return Err(StatsError::EmptyInput(
"no trials, so there is no sampling distribution to have a width",
));
}
let n = T::from_u64(trials).ok_or_else(|| {
StatsError::ConversionFailed("a trial count is not representable in the working scalar")
})?;
Ok((proportion * (T::one() - proportion) / n).sqrt())
}
pub fn bernoulli_proportion<T>(hits: u64, trials: u64) -> Result<(T, T), StatsError>
where
T: RealField + FromPrimitive,
{
if trials == 0 {
return Err(StatsError::EmptyInput(
"a proportion of no trials is undefined",
));
}
if hits > trials {
return Err(StatsError::DimensionMismatch(
"more hits than trials: a proportion cannot exceed one",
));
}
let n = T::from_u64(trials).ok_or_else(|| {
StatsError::ConversionFailed("a trial count is not representable in the working scalar")
})?;
let p = quotient::<T>(hits, trials)?;
let q = quotient::<T>(trials - hits, trials)?;
Ok((p, (p * q / n).sqrt()))
}
fn quotient<T>(numerator: u64, denominator: u64) -> Result<T, StatsError>
where
T: RealField + FromPrimitive,
{
let exact = |v: u64| T::from_u64(v).filter(|t| t.to_u64() == Some(v));
if let (Some(a), Some(b)) = (exact(numerator), exact(denominator)) {
return Ok(a / b);
}
T::from_f64(numerator as f64 / denominator as f64).ok_or_else(|| {
StatsError::ConversionFailed("a count is not representable in the working scalar")
})
}