1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use fpdec::Decimal;

/// Return the minimum of two values
#[inline(always)]
pub(crate) fn min<T>(v0: T, v1: T) -> T
where T: PartialOrd {
    if v0 < v1 {
        v0
    } else {
        v1
    }
}

/// Return the maximum of two values
#[inline(always)]
pub(crate) fn max<T>(v0: T, v1: T) -> T
where T: PartialOrd {
    if v0 > v1 {
        v0
    } else {
        v1
    }
}

/// Convert a `Decimal` value into `f64`.
/// Just used when accuracy is not required.
/// Mainly for `FullTrack` to compute things that are not supported by `Decimal`
/// such as sqrt.
#[inline(always)]
pub(crate) fn decimal_to_f64(val: Decimal) -> f64 {
    if val.n_frac_digits() == 0 {
        return val.coefficient() as f64;
    }
    info!("val: {}, coeff: {}, n_frac_digits: {}", val, val.coefficient(), val.n_frac_digits());

    val.coefficient() as f64 / 10_f64.powi(val.n_frac_digits() as _)
}

#[cfg(test)]
pub(crate) mod tests {
    use std::convert::TryFrom;

    use rand::{thread_rng, Rng};

    use super::*;

    /// round a value to a given precision of decimal places
    /// used in tests
    pub(crate) fn round(val: f64, prec: i32) -> f64 {
        ((val * 10.0_f64.powi(prec)).round()) / 10.0_f64.powi(prec)
    }

    #[test]
    fn test_decimal_to_f64() {
        let _ = pretty_env_logger::try_init();

        assert_eq!(decimal_to_f64(Decimal::ZERO), 0.0);
        assert_eq!(decimal_to_f64(Decimal::ONE), 1.0);
        assert_eq!(decimal_to_f64(Decimal::TWO), 2.0);

        let mut rng = thread_rng();
        const ROUNDING: i32 = 8;
        for _i in 0..1_000 {
            let val: f64 = rng.gen();
            assert_eq!(
                round(decimal_to_f64(Decimal::try_from(val).unwrap()), ROUNDING),
                round(val, ROUNDING)
            );
            assert_eq!(
                round(decimal_to_f64(Decimal::try_from(val * 10.0).unwrap()), ROUNDING),
                round(val * 10.0, ROUNDING)
            );
            assert_eq!(
                round(decimal_to_f64(Decimal::try_from(val * 100.0).unwrap()), ROUNDING),
                round(val * 100.0, ROUNDING)
            );
        }
    }
}