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

**URL:** <https://discourse.julialang.org/t/finite-difference-approximation-using-calculus-getting-the-values-f-x-f-x-e-f-x-e/5681>\
**Category:** Numerics\
**Tags:** differentiation\
**Created:** [September 2, 2017, 4:48pm UTC](https://discourse.julialang.org/t/finite-difference-approximation-using-calculus-getting-the-values-f-x-f-x-e-f-x-e/5681 "2017-09-02T16:48:12Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![vgdev](https://avatars.discourse-cdn.com/v4/letter/v/47e85d/32.png) [@vgdev](https://discourse.julialang.org/u/vgdev)\
**Post date:** [September 2, 2017, 4:48pm UTC](https://discourse.julialang.org/t/finite-difference-approximation-using-calculus-getting-the-values-f-x-f-x-e-f-x-e/5681/1 "2017-09-02T16:48:12Z")

</div>

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
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

```

---

<div class="post-metadata">

**Author:** ![cstjean](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cstjean/32/1444_2.png) [@cstjean](https://discourse.julialang.org/u/cstjean)\
**Post date:** [September 3, 2017, 1:10am UTC](https://discourse.julialang.org/t/finite-difference-approximation-using-calculus-getting-the-values-f-x-f-x-e-f-x-e/5681/2 "2017-09-03T01:10:17Z")

</div>

It’s clearly not ideal, but you could memoize `f` (for instance with [Memoize.jl](https://github.com/simonster/Memoize.jl)), then your extra call to `f` would be cheap.
