Commit 8312383ffa0ea0290f2911fcba0aa3b62f5046bf

Authored by Georg Hopp
1 parent c99cc1ee

continuous sqrt now uses a slice internally

Showing 1 changed file with 7 additions and 12 deletions
@@ -31,28 +31,23 @@ impl Continuous { @@ -31,28 +31,23 @@ impl Continuous {
31 // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots# 31 // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#
32 // Continued_fraction_expansion 32 // Continued_fraction_expansion
33 pub fn sqrt(x :i64, a0 :i64) -> Self { 33 pub fn sqrt(x :i64, a0 :i64) -> Self {
34 - fn inner(mut v :Vec<i64>,  
35 - x :i64,  
36 - a0 :i64,  
37 - mn :i64,  
38 - dn :i64,  
39 - an :i64) -> Vec<i64> { 34 + fn inner(v :&mut [i64], x :i64, a0 :i64, mn :i64, dn :i64, an :i64) {
40 let mn_1 = dn * an - mn; 35 let mn_1 = dn * an - mn;
41 let dn_1 = (x - mn_1 * mn_1) / dn; 36 let dn_1 = (x - mn_1 * mn_1) / dn;
42 let an_1 = (a0 + mn_1) / dn_1; 37 let an_1 = (a0 + mn_1) / dn_1;
43 38
44 - v.push(an);  
45 - 39 + v[0] = an;
46 // The convergence criteria „an_1 == 2 * a0“ is not good for 40 // The convergence criteria „an_1 == 2 * a0“ is not good for
47 // very small x thus I decided to break the iteration at constant 41 // very small x thus I decided to break the iteration at constant
48 // time. Which is the 10 below. 42 // time. Which is the 10 below.
49 - match v.len() {  
50 - 10 => v,  
51 - _ => inner(v, x, a0, mn_1, dn_1, an_1), 43 + if v.len() > 1 {
  44 + inner(&mut v[1..], x, a0, mn_1, dn_1, an_1);
52 } 45 }
53 } 46 }
54 47
55 - Continuous(inner(Vec::new(), x, a0, 0, 1, a0)) 48 + let mut v :Vec<i64> = vec!(0; 10);
  49 + inner(&mut v, x, a0, 0, 1, a0);
  50 + Continuous(v)
56 } 51 }
57 } 52 }
58 53
Please register or login to post a comment