Skip to content

Commit bc87e50

Browse files
authored
Refactor power_by_squaring code (#363)
1 parent 34d0fea commit bc87e50

File tree

1 file changed

+33
-42
lines changed

1 file changed

+33
-42
lines changed

src/power.jl

Lines changed: 33 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ end
6060

6161
# in-place form of power_by_squaring
6262
# this method assumes `y`, `x` and `aux` are of same order
63-
# TODO: add power_by_squaring! method for HomogeneousPolynomial
63+
# TODO: add power_by_squaring! method for HomogeneousPolynomial and mixtures
6464
for T in (:Taylor1, :TaylorN)
6565
@eval function power_by_squaring!(y::$T{T}, x::$T{T}, aux::$T{T},
6666
p::Integer) where {T<:NumberNotSeries}
@@ -99,8 +99,39 @@ end
9999

100100
# power_by_squaring; slightly modified from base/intfuncs.jl
101101
# Licensed under MIT "Expat"
102-
for T in (:Taylor1, :TaylorN)
102+
for T in (:Taylor1, :HomogeneousPolynomial, :TaylorN)
103103
@eval function power_by_squaring(x::$T, p::Integer)
104+
if p == 0
105+
return one(x)
106+
elseif p == 1
107+
return copy(x)
108+
elseif p == 2
109+
return square(x)
110+
elseif p == 3
111+
return x*square(x)
112+
end
113+
t = trailing_zeros(p) + 1
114+
p >>= t
115+
while (t -= 1) > 0
116+
x = square(x)
117+
end
118+
y = x
119+
while p > 0
120+
t = trailing_zeros(p) + 1
121+
p >>= t
122+
while (t -= 1) 0
123+
x = square(x)
124+
end
125+
y *= x
126+
end
127+
return y
128+
end
129+
end
130+
131+
# power_by_squaring specializations for non-mixed Taylor1 and TaylorN
132+
# uses internally mutating method `power_by_squaring!`
133+
for T in (:Taylor1, :TaylorN)
134+
@eval function power_by_squaring(x::$T{T}, p::Integer) where {T <: NumberNotSeries}
104135
(p == 0) && return one(x)
105136
(p == 1) && return copy(x)
106137
(p == 2) && return square(x)
@@ -111,46 +142,6 @@ for T in (:Taylor1, :TaylorN)
111142
return y
112143
end
113144
end
114-
function power_by_squaring(x::HomogeneousPolynomial, p::Integer)
115-
(p == 0) && return one(x)
116-
(p == 1) && return copy(x)
117-
(p == 2) && return square(x)
118-
(p == 3) && return x*square(x)
119-
t = trailing_zeros(p) + 1
120-
p >>= t
121-
while (t -= 1) > 0
122-
x = square(x)
123-
end
124-
y = x
125-
while p > 0
126-
t = trailing_zeros(p) + 1
127-
p >>= t
128-
while (t -= 1) 0
129-
x = square(x)
130-
end
131-
y *= x
132-
end
133-
return y
134-
end
135-
136-
137-
function power_by_squaring(x::TaylorN{Taylor1{T}}, p::Integer) where {T<:NumberNotSeries}
138-
t = trailing_zeros(p) + 1
139-
p >>= t
140-
while (t -= 1) > 0
141-
x = square(x)
142-
end
143-
y = x
144-
while p > 0
145-
t = trailing_zeros(p) + 1
146-
p >>= t
147-
while (t -= 1) 0
148-
x = square(x)
149-
end
150-
y *= x
151-
end
152-
return y
153-
end
154145

155146
## Real power ##
156147
function ^(a::Taylor1{T}, r::S) where {T<:Number, S<:Real}

0 commit comments

Comments
 (0)