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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
use core::str::FromStr;
use std::ops::{Add, AddAssign};
use std::mem::swap;
use std::fmt;
use num_traits::{float::FloatCore, Num, Signed, NumRef, RefNum, CheckedAdd, CheckedMul};
use num_integer::{Integer};
use num_rational::Ratio;
use crate::traits::{RationalApproximation, Approximation, WithSigned};
#[derive(Clone, Debug, PartialEq)]
pub struct ContinuedFraction<T> {
a_coeffs: Vec<T>,
p_coeffs: Vec<T>,
negative: bool
}
impl<T> ContinuedFraction<T> {
#[inline]
pub fn aperiodic_coeffs(&self) -> &[T] {
&self.a_coeffs[..]
}
#[inline]
pub fn periodic_coeffs(&self) -> &[T] {
&self.p_coeffs[..]
}
#[inline]
pub fn is_negative(&self) -> bool {
self.negative
}
#[inline]
pub fn is_rational(&self) -> bool {
self.p_coeffs.len() == 0
}
#[inline]
pub fn is_integer(&self) -> bool {
self.a_coeffs.len() == 1 && self.p_coeffs.len() == 0
}
}
pub struct Coefficients<'a, T> {
a_iter: Option<std::slice::Iter<'a, T>>,
p_ref: &'a Vec<T>,
p_iter: Option<std::slice::Iter<'a, T>>
}
impl<'a, T> Iterator for Coefficients<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if let Some(it) = self.a_iter.as_mut() {
match it.next() {
Some(v) => Some(v),
None => {
self.a_iter = None;
if self.p_ref.len() > 0 {
let mut new_iter = self.p_ref.iter();
let result = new_iter.next();
self.p_iter = Some(new_iter);
result
} else { None }
}
}
} else {
if let Some(it) = self.p_iter.as_mut() {
match it.next() {
Some(v) => Some(v),
None => {
let mut new_iter = self.p_ref.iter();
let result = new_iter.next();
self.p_iter = Some(new_iter);
result
}
}
} else {
None
}
}
}
}
pub struct Convergents<'a, T> {
coeffs: Coefficients<'a, T>,
pm1: T,
pm2: T,
qm1: T,
qm2: T,
neg: bool
}
impl<T: Num> ContinuedFraction<T> {
pub fn new(a_coeffs: Vec<T>, p_coeffs: Vec<T>, negative: bool) -> Self {
let mut dedup_a = Vec::with_capacity(a_coeffs.len());
let mut last_zero = false;
for a in a_coeffs {
if last_zero {
if a.is_zero() {
continue;
}
last_zero = false;
} else {
if a.is_zero() {
last_zero = true;
}
}
dedup_a.push(a);
}
if dedup_a.len() == 0 && p_coeffs.len() == 0 {
panic!("at least one coefficient is required!")
}
ContinuedFraction { a_coeffs: dedup_a, p_coeffs, negative }
}
pub fn coeffs(&self) -> Coefficients<T> {
Coefficients {
a_iter: Some(self.a_coeffs.iter()),
p_ref: &self.p_coeffs, p_iter: None
}
}
}
impl<'a, T: Integer + Clone + CheckedAdd + CheckedMul + WithSigned<Signed = U>,
U: Integer + Clone + Signed>
Iterator for Convergents<'a, T> {
type Item = Ratio<U>;
fn next(&mut self) -> Option<Self::Item> {
let a = self.coeffs.next()?;
let p = a.checked_mul(&self.pm1).and_then(|v| v.checked_add(&self.pm2))?;
let q = a.checked_mul(&self.qm1).and_then(|v| v.checked_add(&self.qm2))?;
swap(&mut self.pm2, &mut self.pm1);
swap(&mut self.qm2, &mut self.qm1);
self.pm1 = p.clone(); self.qm1 = q.clone();
let r = Ratio::new(p.to_signed(), q.to_signed());
if self.neg { Some(-r) } else { Some(r) }
}
}
impl<T: Integer + Clone + CheckedAdd + CheckedMul + WithSigned<Signed = U>,
U: Integer + Clone + Signed> ContinuedFraction<T> {
pub fn convergents(&self) -> Convergents<T> {
Convergents {
coeffs: self.coeffs(),
pm1: T::one(), pm2: T::zero(), qm1: T::zero(), qm2: T::one(),
neg: self.negative
}
}
#[inline]
pub fn to_rational(&self) -> Approximation<Ratio<U>> {
if self.is_rational() {
Approximation::Exact(self.convergents().last().unwrap())
} else {
Approximation::Approximated(self.convergents().nth(
self.a_coeffs.len() + self.p_coeffs.len()).unwrap())
}
}
}
impl<T: Integer + Clone + CheckedAdd + CheckedMul + WithSigned<Signed = U>,
U: Integer + Clone + Signed + CheckedAdd>
RationalApproximation<U> for ContinuedFraction<T>
{
fn approx_rational(&self, limit: &U) -> Approximation<Ratio<U>> {
let within_limit = |v: &U| if v >= &U::zero() { v < limit } else { limit.checked_add(v).unwrap() >= U::zero() };
let ratio_within_limit = |v: &Ratio<U>| within_limit(v.numer()) && within_limit(v.denom());
let mut convergents = self.convergents();
let mut last_conv = convergents.next().unwrap();
if !ratio_within_limit(&last_conv) {
let i = self.a_coeffs.first().unwrap().clone();
return Approximation::Approximated(Ratio::from(i.to_signed()))
}
loop {
last_conv = match convergents.next() {
Some(v) => if ratio_within_limit(&v) { v }
else { return Approximation::Approximated(last_conv); },
None => return Approximation::Exact(last_conv)
}
}
}
}
impl<T: fmt::Display> fmt::Display for ContinuedFraction<T>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.negative { write!(f, "-")?; }
write!(f, "[{}", self.a_coeffs.first().unwrap())?;
if self.a_coeffs.len() == 1 {
if self.p_coeffs.len() == 0 {
return write!(f, "]")
} else {
write!(f, "; ")?;
}
} else {
let mut aiter = self.a_coeffs.iter().skip(1);
write!(f, "; {}", aiter.next().unwrap())?;
while let Some(v) = aiter.next() {
write!(f, ", {}", v)?;
}
if self.p_coeffs.len() > 0 {
write!(f, ", ")?;
}
}
if self.p_coeffs.len() > 0 {
let mut piter = self.p_coeffs.iter();
write!(f, "({}", piter.next().unwrap())?;
while let Some(v) = piter.next() {
write!(f, ", {}", v)?;
}
write!(f, ")]")
} else {
write!(f, "]")
}
}
}
impl<T> ContinuedFraction<T> {
pub fn from_float<U: FloatCore>(f: U) -> Option<Self> {
unimplemented!()
}
pub fn from_rational(f: Ratio<T>) -> Option<Self> {
unimplemented!()
}
pub fn generalize(self) {
unimplemented!()
}
}
pub struct ParseContFracError {
}
impl<T> FromStr for ContinuedFraction<T> {
type Err = ParseContFracError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
unimplemented!()
}
}
pub struct GeneralContinuedFraction<T, FnA: Fn(usize) -> Option<T>, FnB: Fn(usize) -> Option<T>> {
a_pattern: FnA,
b_pattern: FnB
}
impl<T: AddAssign> Add<T> for ContinuedFraction<T> {
type Output = Self;
fn add(self, rhs: T) -> Self {
let mut new_a = self.a_coeffs;
let i = new_a.first_mut().unwrap();
*i += rhs;
ContinuedFraction { a_coeffs: new_a, p_coeffs: self.p_coeffs, negative: self.negative }
}
}
impl<T> Add<Ratio<T>> for ContinuedFraction<T> {
type Output = Self;
fn add(self, rhs: Ratio<T>) -> Self { unimplemented!() }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cont_frac_iter_test() {
let one = ContinuedFraction::<u32>::new(vec![1], vec![], false);
assert_eq!(one.coeffs().map(|&v| v).collect::<Vec<_>>(), vec![1]);
assert_eq!(one.convergents().collect::<Vec<_>>(), vec![Ratio::from(1)]);
let n_one = ContinuedFraction::<u32>::new(vec![1], vec![], true);
assert_eq!(n_one.coeffs().map(|&v| v).collect::<Vec<_>>(), vec![1]);
assert_eq!(n_one.convergents().collect::<Vec<_>>(), vec![Ratio::from(-1)]);
let sq2 = ContinuedFraction::<u32>::new(vec![1], vec![2], false);
assert_eq!(sq2.coeffs().take(5).map(|&v| v).collect::<Vec<_>>(), vec![1, 2, 2, 2, 2]);
assert_eq!(sq2.convergents().take(5).collect::<Vec<_>>(),
vec![Ratio::from(1), Ratio::new(3, 2), Ratio::new(7, 5), Ratio::new(17, 12), Ratio::new(41, 29)]);
let n_sq2 = ContinuedFraction::<u32>::new(vec![1], vec![2], true);
assert_eq!(n_sq2.coeffs().take(5).map(|&v| v).collect::<Vec<_>>(), vec![1, 2, 2, 2, 2]);
assert_eq!(n_sq2.convergents().take(5).collect::<Vec<_>>(),
vec![Ratio::from(-1), Ratio::new(-3, 2), Ratio::new(-7, 5), Ratio::new(-17, 12), Ratio::new(-41, 29)]);
}
#[test]
fn fmt_test() {
assert_eq!(format!("{}", ContinuedFraction::new(vec![1], vec![], false)), "[1]");
assert_eq!(format!("{}", ContinuedFraction::new(vec![1, 2, 3], vec![], false)), "[1; 2, 3]");
assert_eq!(format!("{}", ContinuedFraction::new(vec![1], vec![2], false)), "[1; (2)]");
assert_eq!(format!("{}", ContinuedFraction::new(vec![1, 2, 3], vec![3, 2], false)), "[1; 2, 3, (3, 2)]");
}
}