Skip to content

Special case x^0 #331

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 19, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/dual.jl
Original file line number Diff line number Diff line change
Expand Up @@ -408,8 +408,12 @@ for f in (:(Base.:^), :(NaNMath.pow))
begin
v = value(x)
expv = ($f)(v, y)
deriv = y * ($f)(v, y - 1)
return Dual{Tx}(expv, deriv * partials(x))
if y == zero(y)
new_partials = zero(partials(x))
else
new_partials = partials(x) * y * ($f)(v, y - 1)
end
return Dual{Tx}(expv, new_partials)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. I think the main concern here is performance/SIMDability.

A cleaner way to write this that might be easier on the compiler is

new_partials = ifelse(iszero(y), zero(partials(x)), partials(x) * y * ($f)(v, y - 1))

It'd be worth benchmarking this/looking at generated LLVM code to ensure there aren't any substantial regressions.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, I'll do some benchmarks.

I guess we can also define Base.literal_pow to do the branching at the compile time for some extra boost. Though it only works for the case exponent is an integer literal.

end,
begin
v = value(y)
Expand Down
10 changes: 10 additions & 0 deletions test/DualTest.jl
Original file line number Diff line number Diff line change
Expand Up @@ -455,4 +455,14 @@ for N in (0,3), M in (0,4), V in (Int, Float32)
end
end

@testset "Exponentiation of zero" begin
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought to mix this with the rest of the test but then can't think of a good way to turn this into a random test. So I created a separated testset. I also noticed that @testset is not used anywhere but I assumed that's only because ForwardDiff.jl predates @testset. I hope using @testset is OK.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup, that's fine.

x0 = 0.0
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)
end

end # module