Skip to content

Commit

Permalink
Add antidifferentiation for polynomials
Browse files Browse the repository at this point in the history
  • Loading branch information
chrhansk committed Apr 2, 2024
1 parent e96c595 commit 611881a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/anti_diff.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,19 @@ function MP.antidifferentiate(m::Monomial{V,M}, x::Variable{V,M}) where {V,M}
Monomial(MP.variables(m), z) / (m.z[i] + 1)
end
end

function MP.antidifferentiate(p::Polynomial{V,M,T}, x::Variable{V,M}) where {V,M,T}
i = something(findfirst(isequal(x), MP.variables(p)), 0)
S = typeof(zero(T) * 0)
if iszero(i)
x * p
else
Z = copy.(p.x.Z)
a = Vector{S}(undef, length(p.a))
for j in 1:length(Z)
a[j] = p.a[j] / (Z[j][i] + 1)
Z[j][i] += 1
end
Polynomial(a, MonomialVector(MP.variables(p), Z))
end
end
16 changes: 16 additions & 0 deletions test/poly.jl
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,22 @@
@inferred polynomial(2.0u, Int)
end

@testset "Antiderivative" begin
@polyvar x y

p = (x^2 + 4*y^3)
pi = DynamicPolynomials.antidifferentiate(p, y)
@test pi == (x^2*y + y^4)

p = 2*y
pi = DynamicPolynomials.antidifferentiate(p, y)
@test pi == y^2

p = x^2
pi = DynamicPolynomials.antidifferentiate(p, y)
@test pi == x^2*y
end

@testset "Evaluation" begin
@polyvar x y
@test (x^2 + y^3)(2, 3) == 31
Expand Down

0 comments on commit 611881a

Please sign in to comment.