Created
October 4, 2018 23:34
-
-
Save YingboMa/eb7c3fb0f37b49cf04c4783acd8e45af to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using ReverseDiff, ForwardDiff | |
using Test | |
""" | |
vecjac(f, x, v) -> u | |
``v'J(f(x))`` | |
""" | |
function vecjac(f, x, v) | |
tp = ReverseDiff.InstructionTape() | |
tx = ReverseDiff.track(x, tp) | |
ty = f(tx) | |
ReverseDiff.increment_deriv!(ty, v) | |
ReverseDiff.reverse_pass!(tp) | |
return ReverseDiff.deriv(tx)' | |
end | |
""" | |
jacvec(f, x, v) -> u | |
``J(f(x))*v`` | |
""" | |
function jacvec(f, x, v) | |
du = ForwardDiff.Dual{:___jacvec_tag}.(x, v) | |
ForwardDiff.partials.(f(du), 1) | |
end | |
f = cumprod | |
x = rand(300) | |
v = rand(300) | |
@test jacvec(f, x, v) ≈ ForwardDiff.jacobian(f, x)*v | |
@test vecjac(f, x, v) ≈ v'ForwardDiff.jacobian(f, x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment