Skip to content

Commit

Permalink
Add WeibullError
Browse files Browse the repository at this point in the history
  • Loading branch information
FreezyLemon committed Aug 16, 2024
1 parent 2d9f21d commit 426a93f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 12 deletions.
2 changes: 1 addition & 1 deletion src/distribution/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pub use self::poisson::{Poisson, PoissonError};
pub use self::students_t::{StudentsT, StudentsTError};
pub use self::triangular::{Triangular, TriangularError};
pub use self::uniform::{Uniform, UniformError};
pub use self::weibull::Weibull;
pub use self::weibull::{Weibull, WeibullError};

mod bernoulli;
mod beta;
Expand Down
45 changes: 34 additions & 11 deletions src/distribution/weibull.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::consts;
use crate::distribution::{Continuous, ContinuousCDF};
use crate::function::gamma;
use crate::statistics::*;
use crate::{consts, Result, StatsError};
use rand::Rng;
use std::f64;

Expand All @@ -27,6 +27,26 @@ pub struct Weibull {
scale_pow_shape_inv: f64,
}

#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
pub enum WeibullError {
/// The shape is NaN, zero, or less than zero.
ShapeInvalid,

/// The scale is NaN, zero, or less than zero.
ScaleInvalid,
}

impl std::fmt::Display for WeibullError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
WeibullError::ShapeInvalid => write!(f, "Shape is NaN, zero, or less than zero."),
WeibullError::ScaleInvalid => write!(f, "Scale is NaN, zero, or less than zero."),
}
}
}

impl std::error::Error for WeibullError {}

impl Weibull {
/// Constructs a new weibull distribution with a shape (k) of `shape`
/// and a scale (λ) of `scale`
Expand All @@ -47,17 +67,20 @@ impl Weibull {
/// result = Weibull::new(0.0, 0.0);
/// assert!(result.is_err());
/// ```
pub fn new(shape: f64, scale: f64) -> Result<Weibull> {
let is_nan = shape.is_nan() || scale.is_nan();
match (shape, scale, is_nan) {
(_, _, true) => Err(StatsError::BadParams),
(_, _, false) if shape <= 0.0 || scale <= 0.0 => Err(StatsError::BadParams),
(_, _, false) => Ok(Weibull {
shape,
scale,
scale_pow_shape_inv: scale.powf(-shape),
}),
pub fn new(shape: f64, scale: f64) -> Result<Weibull, WeibullError> {
if shape.is_nan() || shape <= 0.0 {
return Err(WeibullError::ShapeInvalid);
}

if scale.is_nan() || scale <= 0.0 {
return Err(WeibullError::ScaleInvalid);
}

Ok(Weibull {
shape,
scale,
scale_pow_shape_inv: scale.powf(-shape),
})
}

/// Returns the shape of the weibull distribution
Expand Down

0 comments on commit 426a93f

Please sign in to comment.