diff --git a/src/differentiation.jl b/src/differentiation.jl index d62c2750..04e12cfb 100644 --- a/src/differentiation.jl +++ b/src/differentiation.jl @@ -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} diff --git a/test/differentiation.jl b/test/differentiation.jl index 53d58a79..da321c06 100644 --- a/test/differentiation.jl +++ b/test/differentiation.jl @@ -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