Compute derivatives, gradients, Jacobians, and Hessians with ForwardDiff
masterForwardDiff implements forward-mode automatic differentiation (AD) to compute various derivatives of native Julia functions or any callable object.
When to use ForwardDiff:
- It is highly accurate and generally faster than non-AD algorithms.
- It is an excellent choice for functions mapping a scalar to a vector (e.g.,
g(y::Real) -> Vector). - For functions mapping a vector to a scalar (e.g.,
f(x::Vector) -> Scalar), ForwardDiff is a good choice if the input vectorxis not too large, as the implementation is simpler than reverse-mode AD.
using ForwardDiff
# Example: Gradient and Hessian of a scalar-valued function
f(x::Vector) = sin(x[1]) + prod(x[2:end])
x = vcat(pi/4, 2:4)
g = ForwardDiff.gradient(f, x)
H = ForwardDiff.hessian(f, x)
# Example: Derivative of a vector-valued function
g_vec(y::Real) = [sin(y), cos(y), tan(y)]
d = ForwardDiff.derivative(g_vec, pi/4)
# Example: Jacobian using an anonymous function
J = ForwardDiff.jacobian(x) do x
[sin(x[1]), prod(x[2:end])]
end