The numdiff command finds numerical approximations to derivatives.
numdiff uses Fornberg’s algorithm described in “Generation of Finite Difference Formulas on Arbitrarily Spaced Grids”, Mathematics of Computation, 51(184):699–706, 1988. The complexity of this algorithm is O(n2m) in both time and space. To avoid numerical instabilities, numdiff operates in exact arithmetic.
Note that α0,α1,…,αn do not have to be equally spaced, but they must be mutually different and input in ascending order. There are no restrictions on the choice of x0.
Examples.
X=[0,0.1,0.2,0.4,0.5,0.7,0.8,1] |
f:=unapply(sin(x)*exp(-x),x):; |
X:=[0,0.1,0.2,0.4,0.5,0.7,0.8,1]:; |
Y:=apply(f,X):; |
x0:=1/pi:; |
d:=numdiff(X,Y,x0,2) |
−1.38167652799 |
2.82975186496×10−5 |
f(x)=1− |
| , x∈[0,1], |
f:=unapply(1-1/(1+x^2),x) X:=[(0.05*k)$(k=0..20)]:; Y:=apply(f,X):; numdiff(X,Y,euler_gamma,0,1,2) |
⎡ ⎣ | 0.249912571952,0.649519026356,0.000393517941567 | ⎤ ⎦ |
numdiff can be used for generating custom finite-difference stencils for approximation of derivatives.
Example.
Let X=[−1,0,2,4], Y=[a,b,c,d] and x0=1. To obtain an
approximation formula for the second derivative:
Input:
Output:
| a− |
| + |
|
The approximation is always a linear combination of elements in Y, regardless of X, x0 and m.
Given the lists X=[α0,α1,…,αn] and Y=[β0,β1,…,βn], the Lagrange polynomial passing through points (αk,βk) where k=0,1,…,n can be obtained by setting m=0 and entering a symbol for x0.
Example.
Let X=[−2,0,1] and Y=[2,4,1]:
Input:
Output:
− |
| x2− |
| x+4 |
The same result is obtained by entering lagrange([-2,0,1],[2,4,1],x).