Skip to content

Commit

Permalink
Add rem2pi (#2)
Browse files Browse the repository at this point in the history
Transplanted from JuliaAttic/DiffBase.jl#19.
  • Loading branch information
tkoolen authored and jrevels committed Dec 8, 2017
1 parent de3ba87 commit 5214c50
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/rules.jl
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
@define_diffrule Base.hypot(x, y) = :( $x / hypot($x, $y) ), :( $y / hypot($x, $y) )
@define_diffrule Base.mod(x, y) = :( first(promote(ifelse(isinteger($x / $y), NaN, 1), NaN)) ), :( z = $x / $y; first(promote(ifelse(isinteger(z), NaN, -floor(z)), NaN)) )
@define_diffrule Base.rem(x, y) = :( first(promote(ifelse(isinteger($x / $y), NaN, 1), NaN)) ), :( z = $x / $y; first(promote(ifelse(isinteger(z), NaN, -trunc(z)), NaN)) )
@define_diffrule Base.rem2pi(x, r) = :(1), :NaN

####################
# SpecialFunctions #
Expand Down
18 changes: 18 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ function finitediff(f, x)
return (f(x + ϵ) - f(x - ϵ)) /+ ϵ)
end


non_numeric_arg_functions = [(:Base, :rem2pi, 2)]

for (M, f, arity) in DiffRules.diffrules()
(M, f, arity) non_numeric_arg_functions && continue
if arity == 1
@test DiffRules.hasdiffrule(M, f, 1)
deriv = DiffRules.diffrule(M, f, :x)
Expand All @@ -33,3 +37,17 @@ for (M, f, arity) in DiffRules.diffrules()
end
end
end

# Treat rem2pi separately because of its non-numeric second argument:
derivs = DiffRules.diffrule(:Base, :rem2pi, :x, :y)
for xtype in [:Float64, :BigFloat, :Int64]
for mode in [:RoundUp, :RoundDown, :RoundToZero, :RoundNearest]
@eval begin
x = $xtype(rand(1 : 10))
y = $mode
dx, dy = $(derivs[1]), $(derivs[2])
@test isapprox(dx, finitediff(z -> rem2pi(z, y), float(x)), rtol=0.05)
@test isnan(dy)
end
end
end

0 comments on commit 5214c50

Please sign in to comment.