Skip to content

Instantly share code, notes, and snippets.

@mschauer
Created July 5, 2020 17:39
Show Gist options
  • Select an option

  • Save mschauer/18f543a64f4957ad0a24dae91c4cdc98 to your computer and use it in GitHub Desktop.

Select an option

Save mschauer/18f543a64f4957ad0a24dae91c4cdc98 to your computer and use it in GitHub Desktop.
Partial derivatives
using ForwardDiff: derivative
partiali(f, x, i) = ForwardDiff.partials(f([Dual{}(x[j], 1.0*(i==j)) for j in eachindex(x)]))[]
struct ∂{k, F} <: Function
f::F
∂{k}(f::F) where {k, F} = new{k, F}(f)
end
function (pd::∂{k})(args...) where {k}
N = length(args)
derivative(argk -> f(ntuple(i -> i == k ? argk : args[i], Val(N))...), args[k])
end
f(x, y, z, w) = x + 2y + 3z + 4w
∂{3}(f)(1,1,1,1)
#+RESULTS:
: 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment