Skip to content

Commit 889e1fb

Browse files
authored
special case immutable poly powers (#529)
1 parent 28f31f7 commit 889e1fb

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

src/polynomial-container-types/immutable-dense-polynomial.jl

+5
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,11 @@ function ImmutableDensePolynomial{B,T,X,N}(xs::NTuple{M,S}) where {B,T,S,X,N,M}
2929
convert(ImmutableDensePolynomial{B,T,X,N}, ImmutableDensePolynomial{B,T,X,M}(xs))
3030
end
3131

32+
# vector case with N
33+
function ImmutableDensePolynomial{B,T,X,N}(xs::AbstractVector{S}) where {B,T,S,X,N}
34+
ImmutableDensePolynomial{B,T,X,N}(ntuple(Base.Fix1(getindex, xs), Val(N)))
35+
end
36+
3237
# constant
3338
function ImmutableDensePolynomial{B,T,X,N}(c::S) where {B,T,X,N,S<:Scalar}
3439
if N == 0

src/polynomials/standard-basis/immutable-polynomial.jl

+26
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,32 @@ function Base.:*(p::ImmutableDensePolynomial{B,T,X,N},
100100
end
101101

102102

103+
# This can be *really* slow using power_by_squaring the first time. Here we trade off a bit
104+
# julia> p = ImmutablePolynomial(-5:5);
105+
106+
# julia> @time p^15;
107+
# 0.412306 seconds (502.65 k allocations: 34.132 MiB, 6.21% gc time, 99.95% compilation time)
108+
109+
# julia> @time p^15;
110+
# 0.000023 seconds (21 allocations: 5.547 KiB)
111+
112+
# julia> @time Base.power_by_squaring(p,15);
113+
# 43.284660 seconds (20.41 M allocations: 1.013 GiB, 1.31% gc time, 100.00% compilation time)
114+
115+
# julia> @time Base.power_by_squaring(p,15);
116+
# 0.000145 seconds (7 allocations: 6.547 KiB)
117+
# This is not inferrable, as `n` is not a compile time constant
118+
Base.:^(p::ImmutablePolynomial, n::Integer) = immutable_power(p, n)
119+
function immutable_power(p::ImmutablePolynomial{T,X,N}, n::Integer) where {T,X,N}
120+
iszero(p) && return p
121+
isone(N) && return ImmutablePolynomial{T,X,1}(p[0]^n)
122+
qs = (PnPolynomial(p)^n).coeffs
123+
m = length(qs)
124+
N′ = n * (N-1) + 1
125+
z = zero(p[0])
126+
ImmutablePolynomial{T,X,N′}(ntuple(i -> i m ? qs[i] : z, Val(N′)))
127+
end
128+
103129
#
104130
function polynomial_composition(p::ImmutableDensePolynomial{B,T,X,N}, q::ImmutableDensePolynomial{B,S,X,M}) where {B<:StandardBasis,T,S,X,N,M}
105131
P = ImmutableDensePolynomial{B,promote_type(T,S), X, N*M}

0 commit comments

Comments
 (0)