eval_metrics/
numeric.rs

1use std::ops::{Add, Sub, Mul, Div, AddAssign};
2
3///
4/// Represents a scalar value which can either be single (f32) or double (f64) precision
5///
6pub trait Scalar:
7    private::Sealed +
8    Copy +
9    Add<Self, Output=Self> +
10    Sub<Self, Output=Self> +
11    Mul<Self, Output=Self> +
12    Div<Self, Output=Self> +
13    AddAssign +
14    PartialOrd {
15
16    ///
17    /// Computes the absolute value
18    ///
19    fn abs(self) -> Self;
20
21    ///
22    /// Compute the square root
23    ///
24    fn sqrt(self) -> Self;
25
26    ///
27    /// Indicates whether or not the value is finite
28    ///
29    fn is_finite(self) -> bool;
30
31    ///
32    /// Provides a representation of the number zero
33    ///
34    fn zero() -> Self;
35
36    ///
37    /// Provides a representation of the number one
38    ///
39    fn one() -> Self;
40
41    ///
42    /// Constructs a float from an f32 value
43    ///
44    fn from_f32(x: f32) -> Self;
45
46    ///
47    /// Constructs a float from an f64 value
48    ///
49    fn from_f64(x: f64) -> Self;
50
51    ///
52    /// Constructs a float from a usize value
53    ///
54    fn from_usize(x: usize) -> Self;
55}
56
57///
58/// Implementation for f32 single-precision values
59///
60impl Scalar for f32 {
61    fn abs(self) -> Self {self.abs()}
62    fn sqrt(self) -> Self {self.sqrt()}
63    fn is_finite(self) -> bool {self.is_finite()}
64    fn zero() -> Self {0.0_f32}
65    fn one() -> Self {1.0_f32}
66    fn from_f32(x: f32) -> Self {x}
67    fn from_f64(x: f64) -> Self {x as f32}
68    fn from_usize(x: usize) -> Self {x as f32}
69}
70
71///
72/// Implementation for f64 double-precision values
73///
74impl Scalar for f64 {
75    fn abs(self) -> Self {self.abs()}
76    fn sqrt(self) -> Self {self.sqrt()}
77    fn is_finite(self) -> bool {self.is_finite()}
78    fn zero() -> Self {0.0}
79    fn one() -> Self {1.0}
80    fn from_f32(x: f32) -> Self {x as f64}
81    fn from_f64(x: f64) -> Self {x}
82    fn from_usize(x: usize) -> Self {x as f64}
83}
84
85mod private {
86
87    pub trait Sealed {}
88
89    impl Sealed for f32 {}
90    impl Sealed for f64 {}
91}