JuliaDiff / ForwardDiff.jl

Forward Mode Automatic Differentiation for Julia
Other
876 stars 141 forks source link

One call to get f(x) and f'(x)? #630

Open aloispichler opened 1 year ago

aloispichler commented 1 year ago

Excellent package!

Is there a way to get the function value and its derivative in one call? Thanks.

KristofferC commented 1 year ago

Yes, see https://juliadiff.org/ForwardDiff.jl/stable/user/advanced/#Retrieving-Lower-Order-Results.

urbainvaes commented 1 month ago

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: