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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
use crate::{
    core::prelude::*,
    errors::prelude::*,
    extensions::prelude::*,
    numeric::prelude::*,
};

/// ArrayTrait - Array Floating functions
pub trait ArrayFloating<N: Floating> where Self: Sized + Clone {

    /// Returns element-wise True where signbit is set (less than zero)
    ///
    /// # Examples
    ///
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let arr = Array::flat(vec![1., -2., -3., 4.]);
    /// assert_eq!(Array::flat(vec![false, true, true, false]), arr.signbit());
    /// ```
    fn signbit(&self) -> Result<Array<bool>, ArrayError>;

    /// Change the sign of x1 to that of x2, element-wise
    ///
    /// # Arguments
    ///
    /// * `other` - array to copy sign from
    ///
    /// # Examples
    ///
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let arr = Array::flat(vec![1., -2., -3., 4.]);
    /// let other = Array::flat(vec![-1., 2., -3., 4.]);
    /// assert_eq!(Array::flat(vec![-1., 2., -3., 4.]), arr.copysign(&other.unwrap()));
    /// ```
    fn copysign(&self, other: &Array<N>) -> Result<Array<N>, ArrayError>;

    /// Decompose the elements of x into man and twos exp
    ///
    /// # Examples
    ///
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let arr = Array::arange(0., 8., None);
    /// let result = arr.frexp().unwrap();
    /// assert_eq!(Array::flat(vec![0., 0.5, 0.5, 0.75, 0.5, 0.625, 0.75, 0.875, 0.5]).unwrap(), result.0);
    /// assert_eq!(Array::flat(vec![0, 1, 2, 2, 3, 3, 3, 3, 4]).unwrap(), result.1);
    /// ```
    fn frexp(&self) -> Result<(Array<N>, Array<i32>), ArrayError>;

    /// Returns x1 * 2**x2, element-wise. Inverse of frexp
    ///
    /// # Examples
    ///
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let arr = Array::flat(vec![0., 0.5, 0.5, 0.75, 0.5, 0.625, 0.75, 0.875, 0.5]);
    /// let other = Array::flat(vec![0, 1, 2, 2, 3, 3, 3, 3, 4]);
    /// assert_eq!(Array::arange(0., 8., None), arr.ldexp(&other.unwrap()));
    /// ```
    fn ldexp(&self, other: &Array<i32>) -> Result<Array<N>, ArrayError>;

    /// Return the next floating-point value after x1 towards x2, element-wise
    ///
    /// # Examples
    ///
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let expected = Array::flat(vec![1. + f64::EPSILON, 2. - f64::EPSILON]);
    /// assert_eq!(expected, Array::flat(vec![1., 2.]).nextafter(&Array::flat(vec![2., 1.]).unwrap()));
    /// ```
    fn nextafter(&self, other: &Array<N>) -> Result<Array<N>, ArrayError>;

    /// Return the distance between x and the nearest adjacent number
    ///
    /// # Examples
    ///
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// assert_eq!(Array::flat(vec![f64::EPSILON, f64::EPSILON * 2.]), Array::flat(vec![1., 2.]).spacing());
    /// ```
    fn spacing(&self) -> Result<Array<N>, ArrayError>;
}

impl <N: Floating> ArrayFloating<N> for Array<N> {

    fn signbit(&self) -> Result<Array<bool>, ArrayError> {
        self.map(|e| e.to_f64().is_sign_negative())
    }

    fn copysign(&self, other: &Array<N>) -> Result<Array<N>, ArrayError> {
        self.zip(other)?
            .map(|item| N::from(item.0.to_f64().copysign(item.1.to_f64())))
    }

    fn frexp(&self) -> Result<(Array<N>, Array<i32>), ArrayError> {

        fn _frexp(x: f64) -> (f64, i32) {
            let sign = x.signum();
            let mut x = x.abs();
            let mut sig: f64 = 0.0;
            let mut exp: i32 = 0;
            if x == 0.0 { return (sig, exp); }

            while x >= 1.0 { x /= 2.0; exp += 1; }
            while x < 0.5 { x *= 2.0; exp -= 1; }

            sig = x;
            (sig * sign, exp)
        }

        let mut man = vec![];
        let mut exp = vec![];

        self.for_each(|item| {
            let result = _frexp(item.to_f64());
            man.push(N::from(result.0));
            exp.push(result.1);
        })?;

        Ok((
            man.to_array().reshape(&self.get_shape()?)?,
            exp.to_array().reshape(&self.get_shape()?)?,
        ))
    }

    fn ldexp(&self, other: &Array<i32>) -> Result<Array<N>, ArrayError> {

        fn _ldexp(x: f64, exp: i32) -> f64 {
            if x == 0. { return x }
            let mut exp = exp;
            let mut sig = x;

            while exp > 0 { sig *= 2.; exp -= 1; }
            while exp < 0 { sig /= 2.; exp += 1; }

            sig
        }

        self.zip(other)?
            .map(|item| N::from(_ldexp(item.0.to_f64(), item.1)))
    }

    fn nextafter(&self, other: &Array<N>) -> Result<Array<N>, ArrayError> {

        fn _nextafter(x: f64, y: f64) -> f64 {
            if x == y { x }
            else if x < y { x + f64::EPSILON }
            else { x - f64::EPSILON }
        }

        self.zip(other)?
            .map(|item| N::from(_nextafter(item.0.to_f64(), item.1.to_f64())))
    }

    fn spacing(&self) -> Result<Array<N>, ArrayError> {

        fn _spacing(x: f64) -> f64 {
            let bits = x.to_bits();
            let next =
                if x.is_sign_negative() { bits - 1 }
                else { bits + 1 };
            f64::from_bits(next) - x
        }

        self.map(|item| N::from(_spacing(item.to_f64())))
    }
}

impl <N: Floating> ArrayFloating<N> for Result<Array<N>, ArrayError> {

    fn signbit(&self) -> Result<Array<bool>, ArrayError> {
        self.clone()?.signbit()
    }

    fn copysign(&self, other: &Array<N>) -> Result<Array<N>, ArrayError> {
        self.clone()?.copysign(other)
    }

    fn frexp(&self) -> Result<(Array<N>, Array<i32>), ArrayError> {
        self.clone()?.frexp()
    }

    fn ldexp(&self, other: &Array<i32>) -> Result<Array<N>, ArrayError> {
        self.clone()?.ldexp(other)
    }

    fn nextafter(&self, other: &Array<N>) -> Result<Array<N>, ArrayError> {
        self.clone()?.nextafter(other)
    }

    fn spacing(&self) -> Result<Array<N>, ArrayError> {
        self.clone()?.spacing()
    }
}