|
| 1 | +import numpy as numpy |
| 2 | +from scipy.special import factorial |
| 3 | + |
| 4 | +def fdcoeffV(k,xbar,x): |
| 5 | + """ |
| 6 | + fdcoeffV routine modified from Leveque (2007) matlab function |
| 7 | + |
| 8 | + Params: |
| 9 | + ------- |
| 10 | + |
| 11 | + k: int |
| 12 | + order of derivative |
| 13 | + xbar: float |
| 14 | + point at which derivative is to be evaluated |
| 15 | + x: ndarray |
| 16 | + numpy array of coordinates to use in calculating the weights |
| 17 | + |
| 18 | + Returns: |
| 19 | + -------- |
| 20 | + c: ndarray |
| 21 | + array of floats of coefficients. |
| 22 | +
|
| 23 | + Compute coefficients for finite difference approximation for the |
| 24 | + derivative of order k at xbar based on grid values at points in x. |
| 25 | +
|
| 26 | + WARNING: This approach is numerically unstable for large values of n since |
| 27 | + the Vandermonde matrix is poorly conditioned. Use fdcoeffF.m instead, |
| 28 | + which is based on Fornberg's method. |
| 29 | +
|
| 30 | + This function returns a row vector c of dimension 1 by n, where n=length(x), |
| 31 | + containing coefficients to approximate u^{(k)}(xbar), |
| 32 | + the k'th derivative of u evaluated at xbar, based on n values |
| 33 | + of u at x(1), x(2), ... x(n). |
| 34 | +
|
| 35 | + If U is an array containing u(x) at these n points, then |
| 36 | + c.dot(U) will give the approximation to u^{(k)}(xbar). |
| 37 | +
|
| 38 | + Note for k=0 this can be used to evaluate the interpolating polynomial |
| 39 | + itself. |
| 40 | +
|
| 41 | + Requires len(x) > k. |
| 42 | + Usually the elements x(i) are monotonically increasing |
| 43 | + and x(1) <= xbar <= x(n), but neither condition is required. |
| 44 | + The x values need not be equally spaced but must be distinct. |
| 45 | + |
| 46 | + Modified rom http://www.amath.washington.edu/~rjl/fdmbook/ (2007) |
| 47 | + """ |
| 48 | + |
| 49 | + |
| 50 | + n = x.shape[0] |
| 51 | + assert k < n, " The order of the derivative must be less than the stencil width" |
| 52 | + |
| 53 | + # Generate the Vandermonde matrix from the Taylor series |
| 54 | + A = numpy.ones((n,n)) |
| 55 | + xrow = (x - xbar) # displacements x-xbar |
| 56 | + for i in range(1,n): |
| 57 | + A[i,:] = (xrow**(i))/factorial(i); |
| 58 | + |
| 59 | + b = numpy.zeros(n) # b is right hand side, |
| 60 | + b[k] = 1 # so k'th derivative term remains |
| 61 | + |
| 62 | + c = numpy.linalg.solve(A,b) # solve n by n system for coefficients |
| 63 | + |
| 64 | + return c |
0 commit comments