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[[1]] == 0,
expr,
If[ds[[1]] == 1,
(expr /. xs[[1]] -> xs[[1]] + 1) - expr,
FiniteDifference[(expr /. xs[[1]] -> xs[[1]] + 1) -
expr, {xs[[1]]}, {ds[[1]] - 1}]
]
],
FiniteDifference[FiniteDifference[expr, {xs[[1]]}, {ds[[1]]}],
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[123]= f[x]

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

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

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

Out[127]= 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[1]:= DifferenceDelta[f[x], {x, 0}]

Out[1]= f[x]

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

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

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

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

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

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

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

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