Commit 5cd265a6f079ac6dc6853c776e7ab04416b96bea
1 parent
fef11669
Add sqrt approximation for fractionals
Showing
2 changed files
with
34 additions
and
0 deletions
@@ -62,6 +62,33 @@ impl Fractional { | @@ -62,6 +62,33 @@ impl Fractional { | ||
62 | pub fn denominator(self) -> i64 { | 62 | pub fn denominator(self) -> i64 { |
63 | self.1 | 63 | self.1 |
64 | } | 64 | } |
65 | + | ||
66 | + pub fn sqrt(self) -> Self { | ||
67 | + // find the sqrt of x in O(log x/2). | ||
68 | + fn floor_sqrt(x :i64) -> i64 { | ||
69 | + fn inner(l :i64, h :i64, x :i64) -> i64 { | ||
70 | + if l > h { | ||
71 | + l - 1 | ||
72 | + } else { | ||
73 | + let m = (l + h) / 2; | ||
74 | + match x.cmp(&(m * m)) { | ||
75 | + Ordering::Equal => m, | ||
76 | + Ordering::Less => inner(l, m, x), | ||
77 | + Ordering::Greater => inner(m + 1, h, x), | ||
78 | + } | ||
79 | + } | ||
80 | + } | ||
81 | + | ||
82 | + match x.cmp(&0) { | ||
83 | + Ordering::Equal => 0, | ||
84 | + Ordering::Less => -inner(1, -x / 2, -x), | ||
85 | + Ordering::Greater => inner(1, x / 2, x), | ||
86 | + } | ||
87 | + } | ||
88 | + | ||
89 | + let Fractional(n, d) = self; | ||
90 | + Fractional(floor_sqrt(n), floor_sqrt(d)).reduce() | ||
91 | + } | ||
65 | } | 92 | } |
66 | 93 | ||
67 | impl fmt::Display for Fractional { | 94 | impl fmt::Display for Fractional { |
@@ -45,12 +45,19 @@ fn main() { | @@ -45,12 +45,19 @@ fn main() { | ||
45 | let d :f64 = c.try_into().unwrap(); | 45 | let d :f64 = c.try_into().unwrap(); |
46 | let e :f64 = Fractional::try_into(c).unwrap(); | 46 | let e :f64 = Fractional::try_into(c).unwrap(); |
47 | 47 | ||
48 | + let f = Fractional(9, 4); | ||
49 | + let g = Fractional(-9, 4); | ||
50 | + | ||
48 | println!(" [i32] : {:?}" , a); | 51 | println!(" [i32] : {:?}" , a); |
49 | println!(" [Fractional] : {:?}" , b); | 52 | println!(" [Fractional] : {:?}" , b); |
50 | println!(" mean of [i32] : {}" , c); | 53 | println!(" mean of [i32] : {}" , c); |
51 | println!(" as f64 : {}" , d); | 54 | println!(" as f64 : {}" , d); |
52 | println!(" and as f64 : {}" , e); | 55 | println!(" and as f64 : {}" , e); |
53 | println!(" again as f64 : {}" , TryInto::<f64>::try_into(c).unwrap()); | 56 | println!(" again as f64 : {}" , TryInto::<f64>::try_into(c).unwrap()); |
57 | + println!(" sqrt f : {}" , f.sqrt()); | ||
58 | + println!(" sqrt f as f64 : {}" , TryInto::<f64>::try_into(f.sqrt()).unwrap()); | ||
59 | + println!(" sqrt g : {}" , g.sqrt()); | ||
60 | + println!(" sqrt g as f64 : {}" , TryInto::<f64>::try_into(g.sqrt()).unwrap()); | ||
54 | println!(" Rust π : {}" , FPI); | 61 | println!(" Rust π : {}" , FPI); |
55 | println!(" π : {} {}" , TryInto::<f64>::try_into(PI).unwrap(), PI); | 62 | println!(" π : {} {}" , TryInto::<f64>::try_into(PI).unwrap(), PI); |
56 | println!(" π as tuple : {:?}" , TryInto::<(i32, i32)>::try_into(PI).unwrap()); | 63 | println!(" π as tuple : {:?}" , TryInto::<(i32, i32)>::try_into(PI).unwrap()); |
Please
register
or
login
to post a comment