Skip to content

Commit

Permalink
roots and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
moritz committed Jul 7, 2011
1 parent 51d0614 commit 49b4b78
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/core/Complex.pm
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,17 @@ my class Complex is Numeric {
Complex.new($mag * $!im.cos, $mag * $!im.sin);
}

method roots(Complex:D: Int $n) {
return $NaN if $n < 1;
return self if $n == 1;
for $!re, $!im {
return $NaN if $_ eq 'Inf' || $_ eq '-Inf' || $_ eq 'NaN';
}

my ($mag, $angle) = self.polar;
$mag **= 1e0 / $n;
(^$n).map: { $mag.unpolar( ($angle + $_ * 2e0 * pi) / $n) };
}
}

multi sub prefix:<->(Complex \$a) {
Expand Down
7 changes: 7 additions & 0 deletions src/core/Numeric.pm
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
class Complex { ... }

# XXX role Numeric { ... }
my class Numeric {
method Numeric() { self }
Expand All @@ -14,6 +16,7 @@ my class Numeric {
multi method exp(Numeric $base) {
self.exp * $base.log;
}
method roots(Cool $n) { self.Complex.roots($n.Int) }
multi method Bool(Numeric:D:) { self != 0 }

multi method gist(Numeric:D:) { self.Str }
Expand Down Expand Up @@ -61,6 +64,10 @@ proto sub sqrt(|$) {*}
multi sub sqrt(Numeric \$x) { $x.sqrt }
multi sub sqrt(Cool \$x) { $x.Numeric.sqrt }

proto sub roots($, $) { * }
multi sub roots($x, Cool $n) { $x.Numeric.Complex.roots($n.Int) }
multi sub roots($x, Numeric $n) { $x.Numeric.Complex.roots($n.Int) }

proto infix:<+>(|$) { * }
multi infix:<+>($x = 0) { $x.Numeric }
multi infix:<+>(\$a, \$b) { $a.Numeric + $b.Numeric }
Expand Down
1 change: 1 addition & 0 deletions src/core/Real.pm
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ my class Real {
method cis() {
Complex.new(self.cos, self.sin);
}
method Complex() { Complex.new(self.Num, 0e0) }
multi method log() { self.Bridge.log }
multi method log(Real $base) { self.Bridge.log($base.Bridge) }
multi method exp() { self.Bridge.exp }
Expand Down
2 changes: 1 addition & 1 deletion t/spectest.data
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,7 @@ S32-num/power.t
# S32-num/rand.t
S32-num/rat.t
# S32-num/real-bridge.t
# S32-num/roots.t
S32-num/roots.t
# S32-num/rounders.t
# S32-num/sign.t
S32-num/sqrt.t
Expand Down

0 comments on commit 49b4b78

Please sign in to comment.