Skip to content

Commit

Permalink
Add coefficient for polynomial
Browse files Browse the repository at this point in the history
  • Loading branch information
blegat committed Sep 21, 2017
1 parent 24beb92 commit e2fa373
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/term.jl
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,25 @@ termtype(::Union{AbstractVector{PT}, Type{<:AbstractVector{PT}}}, ::Type{T}) whe
Returns the coefficient of the term `t`.
coefficient(p::AbstractPolynomialLike, m::AbstractMonomialLike)
Returns the coefficient of the monomial `m` in `p`.
### Examples
Calling `coefficient` on ``4x^2y`` should return ``4``.
Calling `coefficient(2x + 4y^2 + 3, y^2)` should return ``4``.
Calling `coefficient(2x + 4y^2 + 3, x^2)` should return ``0``.
"""
coefficient(m::AbstractMonomialLike) = 1
function coefficient(p::AbstractPolynomialLike{T}, m::AbstractMonomialLike) where T
for t in terms(p)
if monomial(t) == m
return coefficient(t)
end
end
zero(T)
end

"""
coefficient(p::AbstractPolynomialLike)
Expand Down
3 changes: 3 additions & 0 deletions test/polynomial.jl
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@
@test (@inferred polynomial(p)) isa AbstractPolynomial{Int}
@test (@inferred polynomial(p, Float64)) isa AbstractPolynomial{Float64}

@test coefficient(2x + 4y^2 + 3, y^2) == 4
@test coefficient(2x + 4y^2 + 3, x^2) == 0

@test (@inferred 2x^2*y + 0.0x*y) == 2x^2*y
@test (@inferred 0.0x^2*y + 3x*y) == 3x*y

Expand Down

0 comments on commit e2fa373

Please sign in to comment.