Finite difference approximation using Calculus, getting the values f(x),f(x+e),f(x-e)

differentiation

#1

I have a function f wich is slow to evaluate. So when doing finite differentiating by the use of Calculus.jl in order to approximate \partial f/\partial x \approx \frac{f(x-\epsilon)-f(x)+f(x+\epsilon)}{\epsilon^2}, I also want to be able to retrieve f(x) without doing another call to f. Is there a way to do this?

DiffBase.jl provides this for use with ForwardDiff.jl and ReverseDiff.jl. Example from their docs:

julia> using ForwardDiff, DiffBase

julia> f(x) = sum(sin, x) + prod(tan, x) * sum(sqrt, x);

julia> x = rand(4);

# construct a `DiffResult` with storage for a Hessian, gradient,
# and primal value based on the type and shape of `x`.
julia> result = DiffBase.HessianResult(x)

# Instead of passing an output buffer to `hessian!`, we pass `result`.
# Note that we re-alias to `result` - this is important! See `hessian!`
# docs for why we do this.
julia> result = ForwardDiff.hessian!(result, f, x);

# ...and now we can get all the computed data from `result`
julia> DiffBase.value(result) == f(x)
true

#2

It’s clearly not ideal, but you could memoize f (for instance with Memoize.jl), then your extra call to f would be cheap.