Skip to content

Commit

Permalink
Truncate polynomial if it has zeros in the trailing elements (#12)
Browse files Browse the repository at this point in the history
Truncate polynomial if it has zeros in the trailing elements
  • Loading branch information
giordano committed Sep 23, 2019
2 parents 2f3f009 + b5b05b6 commit 196154b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/PolynomialRoots.jl
Original file line number Diff line number Diff line change
Expand Up @@ -609,8 +609,15 @@ end

function roots(poly::AbstractVector{N}; epsilon::AbstractFloat=NaN,
polish::Bool=false) where {N<:Number}
degree = length(poly) - 1
roots!(zeros(Complex{real(float(N))}, degree), float.(complex(poly)),
# Before starting, truncate the polynomial if it has zeros in the trailing elements
last_nz = findlast(!iszero, poly)
if lastindex(poly) == last_nz
_poly = poly
else
_poly = poly[1:last_nz]
end
degree = length(_poly) - 1
roots!(zeros(Complex{real(float(N))}, degree), float.(complex(_poly)),
epsilon, degree, polish)
end

Expand Down
3 changes: 3 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,9 @@ end
-47.40236121905153, -71.92379520244637, -57.977452001749555]
@test isapprox(zeros(length(poly)-1),
evalpoly(@inferred(roots(poly)), poly), atol = 2e-11)
# https://github.com/giordano/PolynomialRoots.jl/issues/11
poly = [1.0, -2.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]
@test isapprox(@inferred(roots(poly)), [1, 1])
end

@testset "Errors" begin
Expand Down

0 comments on commit 196154b

Please sign in to comment.