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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
use super::block::Block;
use super::simple::InfiniteContinuedFraction;
use crate::traits::{Approximation, Computable};
use num_integer::Integer;
use num_rational::Ratio;
use num_traits::{CheckedAdd, CheckedMul, FromPrimitive, Num, NumRef, RefNum, Signed, ToPrimitive};

/// This trait defines utility functions for generalized continued fraction number
/// `b_1 + a_2 / (b_2 + a_3 / (b_3 + a_4 / .. ))`. They are available for any
/// iterator that returns a pair of number. The first value will be regarded
/// as a_k while the second value as b_k. You need to make sure that a_1 = 1.
pub trait GeneralContinuedFraction<T: Integer + NumRef>: Iterator<Item = (T, T)>
where
    for<'r> &'r T: RefNum<T>,
{
    /// Compute the convergents of the generalized continued fraction
    fn convergents(self) -> Convergents<Self, T>;

    /// Simplify the generalized continued fraction to an `InfiniteContinuedFraction`
    /// Note that usually this function will generate a simple continued fraction with most
    /// coefficients being positive. If you want to ensure the positiveness, you can either
    /// call collect() on `InfiniteContinuedFraction`, or call simplify() again.
    fn simplify(self) -> InfiniteContinuedFraction<Simplified<Self, T>>
    where
        Self: Sized;

    /// Retrieve the decimal representation of the number, as an iterator of digits.
    /// The iterator will stop if the capacity of T is reached
    fn decimals(self) -> DecimalDigits<Self, T>;

    // TODO: we can also implement homo and bihomo function on general continued fraction
    //       however the result will still be an InfiniteContinuedFraction
}

#[derive(Debug, Clone)]
pub struct Convergents<I: Iterator<Item = (T, T)> + ?Sized, T> {
    block: Block<T>,
    g_coeffs: I,
}

#[derive(Debug, Clone)]
pub struct Simplified<I: Iterator<Item = (T, T)> + ?Sized, T> {
    block: Block<T>,
    g_coeffs: I,
}

#[derive(Debug, Clone)]
pub struct DecimalDigits<I: Iterator<Item = (T, T)> + ?Sized, T> {
    block: Block<T>,
    g_coeffs: I,
}

impl<I: Iterator<Item = (T, T)>, T: Integer + NumRef + CheckedAdd + CheckedMul + Clone> Iterator
    for Convergents<I, T>
where
    for<'r> &'r T: RefNum<T>,
{
    type Item = Ratio<T>;

    fn next(&mut self) -> Option<Ratio<T>> {
        let (a, b) = self.g_coeffs.next()?;
        let (p, q) = self.block.checked_gmove(a, b)?;
        self.block.update(p.clone(), q.clone());

        Some(Ratio::new(p, q))
    }
}

impl<I: Iterator<Item = (T, T)>, T: Integer + NumRef> Iterator for Simplified<I, T>
where
    for<'r> &'r T: RefNum<T>,
{
    type Item = T;

    fn next(&mut self) -> Option<T> {
        loop {
            match self.block.reduce_recip() {
                Some(i) => break Some(i),
                None => match self.g_coeffs.next() {
                    Some((a, b)) => self.block.gmove(a, b),
                    None => break None,
                },
            }
        }
    }
}

impl<
        I: Iterator<Item = (T, T)>,
        T: Integer + NumRef + CheckedAdd + CheckedMul + FromPrimitive + ToPrimitive,
    > Iterator for DecimalDigits<I, T>
where
    for<'r> &'r T: RefNum<T>,
{
    type Item = u8;

    fn next(&mut self) -> Option<u8> {
        // TODO: print point and handle signed & integer > 10 case
        loop {
            match self.block.reduce_mul(T::from_u8(10).unwrap()) {
                Some(i) => break Some(i.to_u8().unwrap() + b'0'),
                None => match self.g_coeffs.next() {
                    Some((a, b)) => {
                        let (p, q) = self.block.checked_gmove(a, b)?;
                        self.block.update(p, q);
                    }
                    None => break None,
                },
            }
        }
    }
}

impl<I: Iterator<Item = (T, T)>, T: Integer + NumRef> GeneralContinuedFraction<T> for I
where
    for<'r> &'r T: RefNum<T>,
{
    fn convergents(self) -> Convergents<I, T> {
        Convergents {
            block: Block::identity(),
            g_coeffs: self,
        }
    }

    fn simplify(self) -> InfiniteContinuedFraction<Simplified<Self, T>> {
        InfiniteContinuedFraction(Simplified {
            block: Block::identity(),
            g_coeffs: self,
        })
    }

    fn decimals(self) -> DecimalDigits<Self, T> {
        DecimalDigits {
            block: Block::identity(),
            g_coeffs: self,
        }
    }
}

impl<I: Iterator<Item = (T, T)> + Clone, T: Integer + NumRef + Clone + CheckedAdd + CheckedMul>
    Computable<T> for I
where
    for<'r> &'r T: RefNum<T>,
{
    fn approximated(&self, limit: &T) -> Approximation<Ratio<T>> {
        let mut convergents = self.clone().convergents();
        let mut last_conv = convergents.next().unwrap();
        if last_conv.denom() > limit {
            return Approximation::Approximated(last_conv);
        }
        loop {
            last_conv = match convergents.next() {
                Some(v) => {
                    if v.denom() < limit {
                        v
                    } else {
                        return Approximation::Approximated(last_conv);
                    }
                }
                None => return Approximation::Exact(last_conv),
            }
        }
    }
}

// TODO: implement continued fraction for various functions
// REF: https://crypto.stanford.edu/pbc/notes/contfrac/cheat.html
// List: coth(1/n), tan(1/n), arctan(n), tanh(n), tan(n), log(1+x), exp(2m/n), exp(1/n)

#[derive(Debug, Clone, Copy)]
pub struct ExpCoefficients<T> {
    exponent: T,
    i: T,
}

impl<T: Num + NumRef + Clone + Signed> Iterator for ExpCoefficients<T>
where
    for<'r> &'r T: RefNum<T>,
{
    type Item = (T, T);

    fn next(&mut self) -> Option<Self::Item> {
        let result = if self.i.is_zero() {
            Some((T::one(), T::one()))
        } else if self.i.is_one() {
            Some((self.exponent.clone(), T::one()))
        } else {
            Some((
                -((&self.i - T::one()) * &self.exponent),
                &self.i + &self.exponent,
            ))
        };

        self.i = &self.i + T::one();
        result
    }
}

pub fn exp<T: Num + Signed>(target: T) -> ExpCoefficients<T> {
    ExpCoefficients {
        exponent: target,
        i: T::zero(),
    }
}

// TODO: implement operators to caculate HAKMEM Constant
// https://crypto.stanford.edu/pbc/notes/contfrac/hakmem.html

#[cfg(test)]
mod tests {
    use super::*;
    use crate::symbols::{Pi, E};

    #[test]
    fn general_conf_frac_test() {
        let e = E {};
        assert_eq!(e.cfrac::<i32>().take(10), exp(1).simplify().take(10));

        let pi = Pi {};
        assert_eq!(
            pi.gfrac()
                .convergents()
                .skip(1)
                .take(5)
                .map(|c| c.into())
                .collect::<Vec<(i32, i32)>>(),
            vec![(4, 1), (3, 1), (19, 6), (160, 51), (1744, 555)]
        );
        assert_eq!(
            pi.gfrac().simplify().0.take(6).collect::<Vec<u64>>(),
            vec![3, 7, 15, 1, 292, 1]
        );
        assert_eq!(
            pi.gfrac::<u32>().decimals().take(20).collect::<Vec<_>>(),
            b"31415926"
        );
    }

    #[test]
    fn functions_test() {
        assert_eq!(
            exp(1).take(5).collect::<Vec<_>>(),
            vec![(1, 1), (1, 1), (-1, 3), (-2, 4), (-3, 5)]
        )
    }
}