Skip to content

Commit

Permalink
deflate_leading_zeros fixes (#11)
Browse files Browse the repository at this point in the history
* fix deflate_leading_zeros zero polynomial handling

There were multiple issues with the deflate_leading_zeros code for the
case of a zero polynomial (where all vector elements are zero).

The condition (`N == 0`) was wrong, a check for nothingness is needed
instead as findfirst, findlast return `nothing` when nothing is found.
This resulted in a useless error message from `deflate_leading_zeros`
when `roots` was called with a zero polynomial.

The second return value, whose definition isn't clear, seems like it
was wrong for the zero polynomial case, judging by the fact that it
depended on the number of zero coefficients, even though that number is
irrelevant if all coefficients are zero.

I also changed `zeros(S, 0)` to the simpler `S[]`.

Regarding the replaced condition (`N == 0`), note that logically it
would have been OK to replace it with either `isnothing(N)` or
`isnothing(K)`, but I instead used `isnothing(N) | isnothing(K)` to
help Julia with its type inference for the succeeding part of the
function.

* prevent run time dispatch in deflate_leading_zeros

Seems Julia needs a bit of hand-holding here.

Checked with development versions of Julia and JET.
  • Loading branch information
nsajko authored Dec 14, 2022
1 parent d7154dd commit 472ed45
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions src/utils.jl
Original file line number Diff line number Diff line change
@@ -1,9 +1,21 @@
# Returns a tuple (none_found::Bool, (first::Int, last::Int))
function find_first_last(
pr::P,
v::AbstractVector) where {P <: Function}

first = findfirst(pr, v)
last = findlast(pr, v)

(isnothing(first) | isnothing(last)) && return (true, (0, 0))

(false, (first::Int, last::Int))
end

function deflate_leading_zeros(ps::Vector{S}) where {S}
## trim any 0s from the end of ps
N = findlast(!iszero, ps)
K = findfirst(!iszero, ps)
(is_empty, (K, N)) = find_first_last(!iszero, ps)

is_empty && return (S[], 0)

N == 0 && return(zeros(S,0), length(ps))
# XXX should we make a view?
ps = ps[K:N]
ps, K-1
Expand Down

0 comments on commit 472ed45

Please sign in to comment.