Skip to content

Commit

Permalink
Add Base.literal_pow
Browse files Browse the repository at this point in the history
  • Loading branch information
tkf committed Jul 19, 2018
1 parent 123cc19 commit 855b8fa
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
12 changes: 12 additions & 0 deletions src/dual.jl
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,18 @@ for f in (:(Base.:^), :(NaNMath.pow))
end
end

@inline Base.literal_pow(::typeof(^), x::Dual{T}, ::Type{Val{0}}) where {T} =
Dual{T}(one(value(x)), zero(partials(x)))

for y in 1:3
@eval @inline function Base.literal_pow(::typeof(^), x::Dual{T}, ::Val{$y}) where {T}
v = value(x)
expv = v^$y
deriv = $y * v^$(y - 1)
return Dual{T}(expv, deriv * partials(x))
end
end

# hypot #
#-------#

Expand Down
7 changes: 4 additions & 3 deletions test/DualTest.jl
Original file line number Diff line number Diff line change
Expand Up @@ -460,9 +460,10 @@ end
x1 = Dual{:t1}(x0, 1.0)
x2 = Dual{:t2}(x1, 1.0)
x3 = Dual{:t3}(x2, 1.0)
@test x3^2 === x3 * x3
@test x2^1 === x2
@test x1^0 === Dual{:t1}(1.0, 0.0)
pow = ^ # to call non-literal power
@test pow(x3, 2) === x3^2 === x3 * x3
@test pow(x2, 1) === x2^1 === x2
@test pow(x1, 0) === x1^0 === Dual{:t1}(1.0, 0.0)
end

end # module

0 comments on commit 855b8fa

Please sign in to comment.