# Function to calculate finite difference

I wrote a function to calculate multivariate finite difference of different orders

ClearAll[FiniteDifference];
FiniteDifference[expr_, xs_List, ds_List] := Block[{},
If[Length[xs] == 0,
expr,
If[Length[xs] == 1,
If[
ds[] == 0,
expr,
If[ds[] == 1,
(expr /. xs[] -> xs[] + 1) - expr,
FiniteDifference[(expr /. xs[] -> xs[] + 1) -
expr, {xs[]}, {ds[] - 1}]
]
],
FiniteDifference[FiniteDifference[expr, {xs[]}, {ds[]}],
Rest[xs], Rest[ds]]
]
]
];
FiniteDifference[f[x], {x}, {0}]
FiniteDifference[f[x], {x}, {1}]
FiniteDifference[f[x], {x}, {2}]
FiniteDifference[f[x, y], {x, y}, {0, 1}]
FiniteDifference[f[x, y], {x, y}, {1, 1}]

Out= f[x]

Out= -f[x] + f[1 + x]

Out= f[x] - 2 f[1 + x] + f[2 + x]

Out= -f[x, y] + f[x, 1 + y]

Out= f[x, y] - f[x, 1 + y] - f[1 + x, y] + f[1 + x, 1 + y]


I wonder, is it correct, especially in last sample?

• To answer your question, check the documentation (not very easy to find online): tutorial/NDSolveMethodOfLines - explicit formulas are above the heading for FiniteDifferenceDerivative. Maybe this should be closed as "easily found in the documentation" - but it's not that easy to find, so I could also post an answer if needed (or even better: answer your own question).
– Jens
Nov 26 '14 at 0:42
• Agree with @Jens. This is not easy to find. You have to already know it is there in order to know it is there! But it should solve your problems. Nov 26 '14 at 1:01
• @Jens, I added some keywords to that notebook, so in a future version one should be able to enter relevant search queries and it should then pring up this notebook. Hope that helps a bit. Thanks. Nov 26 '14 at 7:56
• the correct expressioms are easy enough to find en.m.wikipedia.org/wiki/Finite_difference if you just want to validate. you of course need to divide by the deltas. Nov 26 '14 at 13:12
• @user21 Great - thanks. That's a valuable resource, I think.
– Jens
Nov 26 '14 at 16:47

You could try using DifferenceDelta to check your answers for these examples.

In:= DifferenceDelta[f[x], {x, 0}]

Out= f[x]

In:= DifferenceDelta[f[x], x]

Out= -f[x] + f[1 + x]

In:= DifferenceDelta[f[x], {x, 2}]

Out= f[x] - 2 f[1 + x] + f[2 + x]

In:= DifferenceDelta[f[x, y], {x, 0}, {y, 1}]

Out= -f[x, y] + f[x, 1 + y]

In:= DifferenceDelta[f[x, y], x, y]

Out= f[x, y] - f[x, 1 + y] - f[1 + x, y] + f[1 + x, 1 + y]