Skip to content

Instantly share code, notes, and snippets.

@YingboMa
Created October 4, 2018 23:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YingboMa/eb7c3fb0f37b49cf04c4783acd8e45af to your computer and use it in GitHub Desktop.
Save YingboMa/eb7c3fb0f37b49cf04c4783acd8e45af to your computer and use it in GitHub Desktop.
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