Skip to content

Commit ff8fcfe

Browse files
authored
Merge pull request #112 from JuliaAlgebra/feature/coefficient_variables
Add coefficient(p, vars, monomial)
2 parents 93676b9 + ac961c7 commit ff8fcfe

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

docs/src/types.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ polynomialtype
5555
terms
5656
nterms
5757
coefficients
58+
coefficient(p::AbstractPolynomialLike, vars, m::AbstractMonomialLike)
5859
monomials
5960
mindegree
6061
maxdegree

src/term.jl

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,33 @@ function coefficient(p::AbstractPolynomialLike{T}, m::AbstractMonomialLike) wher
7171
zero(T)
7272
end
7373

74+
"""
75+
coefficient(p::AbstractPolynomialLike, m::AbstractMonomialLike, vars)::AbstractPolynomialLike
76+
77+
Returns the coefficient of the monomial `m` of the polynomial `p` considered as a polynomial in variables
78+
`vars`.
79+
80+
### Example
81+
Calling `coefficient((a+b)x^2+2x+y*x^2, x^2, [x,y])` should return `a+b`.
82+
Calling `coefficient((a+b)x^2+2x+y*x^2, x^2, [x])` should return `a+b+y`.
83+
"""
84+
function coefficient(f::APL, m::AbstractMonomialLike, vars)
85+
coeff = zero(f)
86+
for t in terms(f)
87+
match = true
88+
for v in vars
89+
if degree(t, v) != degree(m, v)
90+
match = false
91+
break
92+
end
93+
end
94+
match || continue
95+
96+
coeff += coefficient(t) * (_div(monomial(t), m))
97+
end
98+
coeff
99+
end
100+
74101
"""
75102
coefficient(p::AbstractPolynomialLike)
76103

test/polynomial.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,10 @@ const MP = MultivariatePolynomials
5151
@test coefficient(2x + 4y^2 + 3, y^2) == 4
5252
@test coefficient(2x + 4y^2 + 3, x^2) == 0
5353

54+
Mod.@polyvar a b
55+
@test coefficient((2a + b)x^2 + 2y^2 + 3, x^2, (x,y)) == 2a + b
56+
@test coefficient((2a + b)x^2 + 2y^2 + 3x^2*y, x^2, (x,)) == 2a + b + 3y
57+
5458
@test (@inferred 2x^2*y + 0.0x*y) == 2x^2*y
5559
@test (@inferred 0.0x^2*y + 3x*y) == 3x*y
5660

0 commit comments

Comments
 (0)