Skip to content

Commit

Permalink
Fix differentiation of zero polynomial
Browse files Browse the repository at this point in the history
  • Loading branch information
blegat committed Jan 26, 2021
1 parent bb42dcd commit ddf199b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/differentiation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,15 @@ differentiate(α::T, v::AbstractVariable) where T = zero(T)
differentiate(v1::AbstractVariable, v2::AbstractVariable) = v1 == v2 ? 1 : 0
differentiate(t::AbstractTermLike, v::AbstractVariable) = coefficient(t) * differentiate(monomial(t), v)
# The polynomial function will take care of removing the zeros
differentiate(p::APL, v::AbstractVariable) = polynomial!(differentiate.(terms(p), v), SortedState())
function differentiate(p::APL, v::AbstractVariable)
if iszero(p)
# As `terms(p)` is empty, `differentiate.(terms(p), v)` gives `Any[]`.
T = typeof(differentiate(one(termtype(p)), v))
polynomial!(T[], SortedUniqState())
else
polynomial!(differentiate.(terms(p), v), SortedState())
end
end
differentiate(p::RationalPoly, v::AbstractVariable) = (differentiate(p.num, v) * p.den - p.num * differentiate(p.den, v)) / p.den^2

const ARPL = Union{APL, RationalPoly}
Expand Down
6 changes: 6 additions & 0 deletions test/differentiation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@
@test differentiate(f, [x, y, z]) == [2x 1 0; 4 0 2z]
@test differentiate(f, (x, y, z)) == [2x 1 0; 4 0 2z]

@testset "Differentiate empty polynomial" begin
p = x^0 - 1
@test iszero(@inferred differentiate(p, x))
@test all(iszero, @inferred differentiate(p, [x, y]))
end

@testset "differentiation with Val{}" begin
@test @inferred(differentiate(x, x, Val{0}())) == x
@test @inferred(differentiate(x, x, Val{1}())) == 1
Expand Down

0 comments on commit ddf199b

Please sign in to comment.