Skip to main content

ndarray_glm/
num.rs

1//! numerical trait constraints
2use std::cmp;
3
4use ndarray::NdFloat;
5use ndarray_linalg::Lapack;
6
7// NdFloat covers everything we need except Lapack, which is an ndarray_linalg trait enabling
8// linear algebra.
9pub trait Float: NdFloat + Lapack {
10    // Return 1/2 = 0.5
11    fn half() -> Self;
12
13    // Return 2.0
14    fn two() -> Self;
15
16    /// A more conventional sign function, because the built-in signum treats signed zeros as
17    /// positive and negative: <https://github.com/rust-lang/rust/issues/57543>
18    fn sign(self) -> Self {
19        if self == Self::zero() {
20            Self::zero()
21        } else {
22            self.signum()
23        }
24    }
25
26    /// total_cmp is not implemented in num_traits, so implement it here.
27    fn total_cmp(&self, other: &Self) -> cmp::Ordering;
28}
29
30impl Float for f32 {
31    fn half() -> Self {
32        0.5
33    }
34
35    fn two() -> Self {
36        2.0
37    }
38
39    fn total_cmp(&self, other: &Self) -> cmp::Ordering {
40        self.total_cmp(other)
41    }
42}
43impl Float for f64 {
44    fn half() -> Self {
45        0.5
46    }
47
48    fn two() -> Self {
49        2.0
50    }
51
52    fn total_cmp(&self, other: &Self) -> cmp::Ordering {
53        self.total_cmp(other)
54    }
55}