Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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