Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 51 lines (45 sloc) 1.735 kB
02e626a @colomon Start first continued fraction experiments.
authored
1 use Test;
2
f6739f7 @colomon Couple more (passing!) tests.
authored
3 plan 9;
02e626a @colomon Start first continued fraction experiments.
authored
4
5 sub make-continued-fraction (Real $x is copy) {
6 gather loop {
7 my $a = $x.floor;
8 take $a;
9 $x = $x - $a;
10 last if $x == 0;
11 $x = 1 / $x;
12 }
13 }
14
15 is make-continued-fraction(3), [3], "Sanity test";
16 is make-continued-fraction(-42), [-42], "Sanity test";
17 is make-continued-fraction(3.245), [3, 4, 12, 4], "Wikipedia example works";
18 is make-continued-fraction(-4.2), [-5, 1, 4], "Wikipedia example works";
aff6975 @colomon Implement mjd's example z function.
authored
19
20 sub z($a is copy, $b is copy, $c is copy, $d is copy, @x) {
21 gather loop {
22 # say "abcd: $a $b $c $d";
23 my $a-div-c = $c ?? $a div $c !! Inf;
24 my $b-div-d = $d ?? $b div $d !! Inf;
25 # say "a/c b/d: $a-div-c $b-div-d";
26 last if $a-div-c == Inf && $b-div-d == Inf;
27 if $a-div-c == $b-div-d {
28 my $n = $a-div-c;
29 ($a, $b, $c, $d) = ($c, $d, $a - $c * $n, $b - $d * $n);
30 take $n;
31 # say "took $n";
32 } else {
33 if @x {
34 my $p = @x.shift;
35 ($a, $b, $c, $d) = ($b, $a + $b * $p, $d, $c + $d * $p);
36 # say "hey, $p";
37 } else {
38 ($a, $b, $c, $d) = ($b, $b, $d, $d); # WHY????
39 # say "hey, Inf";
40 }
41 }
42 }
43 }
44
45 is z(1, 2, 2, 0, [1, 5, 2]), [1, 1, 2, 7], "mjd's example works";
46 is z(1, 0, 1, 0, [1, 2, 3, 4]), [1], "z handles case where it is 0 times x";
47 is z(1, 0, 1, 0, [0]), [1], "z handles another case where it is 0 times x";
f6739f7 @colomon Couple more (passing!) tests.
authored
48 is z(1, 4, 4, 0, make-continued-fraction(22/7)), make-continued-fraction(22/7+1/4),
49 "+1/4 works, with make-continued-fraction";
50 is z(1, 0, 0, 1, make-continued-fraction(22/7)), make-continued-fraction(7/22), "z works to get reciprocal";
Something went wrong with that request. Please try again.