ForwardDiff.jl icon indicating copy to clipboard operation
ForwardDiff.jl copied to clipboard

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

Open aloispichler opened this issue 2 years ago • 2 comments

Excellent package!

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

aloispichler avatar Mar 03 '23 11:03 aloispichler

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

KristofferC avatar Mar 03 '23 11:03 KristofferC

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 ForwardDiff has functions derivative and derivative!, there is no function DiffResults.DerivativeResult.

  • Although there is a ! in the function derivative!, this function in the code above does not modify its argument result.

urbainvaes avatar May 27 '24 16:05 urbainvaes