How can I get the second order derivarive of a function using ChainRules? Bellow is my approach for the sin
function.
See the following code:
using ChainRules
using ChainRulesCore
# from the docs, first derivative of sin
x = 1.0
sinx, sin_pullback = rrule(sin, x)
sin_pullback(x) == (NoTangent(), cos(x)) # true
Let’s try to make it more general:
using ChainRules
using ChainRulesCore
sin_pullback(u) = rrule(sin, u)[2]
sin_pullback(pi/4)(1) == (NoTangent(), cos(pi/4)) # true
dsin(u) = sin_pullback(u)(1)[2] # get the cos(u) value
dsin(pi/4) == cos(pi/4) # true
# does not work:
rrule(dsin, pi/4) # returns nothing, we want (cos(pi/4), -sin(pi/4)
This happens because dsin != cos
and there is no rrule defined for dsin
.
So how can we achieve this?