Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
aloispichler opened this issue Mar 3, 2023 · 2 comments
Open

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

aloispichler opened this issue Mar 3, 2023 · 2 comments

Comments

@aloispichler
Copy link

Excellent package!

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

@KristofferC
Copy link
Collaborator

@urbainvaes
Copy link

urbainvaes commented May 27, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants