From 3a69907feeb99c772f2bb65235e453619643e931 Mon Sep 17 00:00:00 2001 From: trizen Date: Mon, 11 Apr 2022 09:29:39 +0300 Subject: [PATCH] - Fixed the conversion of Polynomial objects to Number objects (when 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. --- lib/Sidef/Types/Number/Polynomial.pm | 7 ++--- scripts/Tests/polynomial.sf | 42 ++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/lib/Sidef/Types/Number/Polynomial.pm b/lib/Sidef/Types/Number/Polynomial.pm index cb572d11..0c1b8b6f 100644 --- a/lib/Sidef/Types/Number/Polynomial.pm +++ b/lib/Sidef/Types/Number/Polynomial.pm @@ -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) = @_; @@ -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 { diff --git a/scripts/Tests/polynomial.sf b/scripts/Tests/polynomial.sf index 181d5ef4..77a4ead4 100644 --- a/scripts/Tests/polynomial.sf +++ b/scripts/Tests/polynomial.sf @@ -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!"