Skip to content

Commit

Permalink
- Fixed the conversion of Polynomial objects to Number objects (when …
Browse files Browse the repository at this point in the history
…possible).

Example:

	var a = Poly([3])
	var b = Poly([3,4])

	say a.sqrt	#=> sqrt(3)
	say b.sqrt	#=> NaN

Only polynomials of degree 0 can be converted to a Number. When a Polynomial cannot be converted to a Number, Polynomial.to_n() now returns NaN.
  • Loading branch information
trizen committed Apr 11, 2022
1 parent f1cd9d9 commit 3a69907
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 4 deletions.
7 changes: 3 additions & 4 deletions lib/Sidef/Types/Number/Polynomial.pm
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ package Sidef::Types::Number::Polynomial {
use overload
q{bool} => sub { (@_) = ($_[0]); goto &__boolify__ },
q{""} => sub { (@_) = ($_[0]); goto &__stringify__ },
q{${}} => sub { \$_[0] },
q{0+} => sub { $_[0] };
q{${}} => \&to_n,
q{0+} => \&to_n;

sub new {
my (undef, @args) = @_;
Expand Down Expand Up @@ -73,8 +73,7 @@ package Sidef::Types::Number::Polynomial {
return $x->{0};
}

## return Sidef::Types::Number::Number::ZERO;
return $x; # maybe we should return zero?
return Sidef::Types::Number::Number::nan();
}

sub real {
Expand Down
42 changes: 42 additions & 0 deletions scripts/Tests/polynomial.sf
Original file line number Diff line number Diff line change
Expand Up @@ -303,4 +303,46 @@ assert_eq(Mod(chebyshevT(42), 97)(100), chebyshevTmod(42, 100, 97))
assert_eq(Mod(chebyshevT(42), 97)(15/13), chebyshevT(42, 15/13) % 97)
assert_eq(Mod(chebyshevT(42), 97)(15/13), chebyshevTmod(42, 15/13, 97))

do {

func derivative(f) {
Poly(f.coeffs.map_2d{|e,k| [e-1, k*e] }.flat...)
}

var coeffs = [
[5],
[4,-3],
[-1,6,5],
[-4,3,-2,1],
[-1, 6, 5],
[1,1,0,-1,-1],
]

var got = []

for c in (coeffs) {
var poly = Poly(c.flip)
var derv = derivative(poly)

var d = { derv.coeff(_) }.map(0..derv.degree)

got << d

say "Polynomial : #{'%20s' % c} = #{poly}"
say "Derivative : #{'%20s' % d} = #{derv || 0}\n"
}

assert_eq(
got,
[
[0]
[-3]
[6, 10]
[3, -4, 3]
[6, 10]
[1, 0, -3, -4]
]
)
}

say "** Test passed!"

0 comments on commit 3a69907

Please sign in to comment.