From 6b4ed5502c533e3059a12d099352146d768b30ff Mon Sep 17 00:00:00 2001 From: Twan Koolen Date: Mon, 25 Sep 2017 14:08:01 -0400 Subject: [PATCH] Add rem2pi Transplanted from https://github.com/JuliaDiff/DiffBase.jl/pull/19. --- src/rules.jl | 1 + test/runtests.jl | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/src/rules.jl b/src/rules.jl index d6d58ee..3b76a96 100644 --- a/src/rules.jl +++ b/src/rules.jl @@ -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 # diff --git a/test/runtests.jl b/test/runtests.jl index b108b5b..c892aea 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -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) @@ -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