ForwardDiff.jl
ForwardDiff.jl copied to clipboard
One call to get f(x) and f'(x)?
Excellent package!
Is there a way to get the function value and its derivative in one call? Thanks.
Yes, see https://juliadiff.org/ForwardDiff.jl/stable/user/advanced/#Retrieving-Lower-Order-Results.
Since it took me some time to find this information, here is how I think you can do it
using ForwardDiff
using DiffResults
# Function to differentiate
f(x) = exp(sin(x)^2)
# Create container for result
result = DiffResults.DiffResult(0., 0.)
# Calculate function and derivative at x = 2.0
x = 2.; result = ForwardDiff.derivative!(result, f, x)
@show DiffResults.value(result) == f(x)
@show DiffResults.derivative(result) == ForwardDiff.derivative(f, x)
There are a couple of things I do not find entirely intuitive in this interface:
-
Although
ForwardDiffhas functionsderivativeandderivative!, there is no functionDiffResults.DerivativeResult. -
Although there is a
!in the functionderivative!, this function in the code above does not modify its argumentresult.