简体   繁体   中英

Cubic Spline interpolation implementation

In the following code I am trying to implement the following

  • write a function naturalSpline that implements cubic spline interpolation with natural boundary conditions
  • Use a tridiagonal solver to solve the arising tridiagonal system for the first derivatives.
  • The prototype of the function should read yy=naturalSpline(x,y,xx) where (x,y) are the input points and data, and xx are the points where the data should be interpolated.

I figured first I would start with the second bullet point, creating the tridiagonal solver. So this is just the Thomas algorithm. I spent some time to create this part of the code and I have formatted it below. But now I am trying to finish the first and third bullet points but I am not sure how to use what I have done already to finish those. Looking for some help with this! Thanks in advance.

import numpy as np
def TDMA(a,b,c,d):
    n = len(d)
    w= np.zeros(n-1,float)
    g= np.zeros(n, float)
    p = np.zeros(n,float)

    w[0] = c[0]/b[0]
    g[0] = d[0]/b[0]

    for i in range(1,n-1):
        w[i] = c[i]/(b[i] - a[i-1]*w[i-1])
    for i in range(1,n):
        g[i] = (d[i] - a[i-1]*g[i-1])/(b[i] - a[i-1]*w[i-1])
    p[n-1] = g[n-1]
    for i in range(n-1,0,-1):
        p[i-1] = g[i-1] - w[i-1]*p[i]
    return p
A = np.array([[10,2,0,0],[3,10,4,0],[0,1,7,5],   [0,0,3,4]],dtype=float)   
a = np.array([3.,1,3]) 
b = np.array([10.,10.,7.,4.])
c = np.array([2.,4.,5.])
d = np.array([3,4,5,6.])
print (TDMA(a, b, c, d))

Which gives the correct output, I even tested it against np.linalg.solve(a,b,c,d) to make sure it was correct

[ 0.14877589  0.75612053 -1.00188324  2.25141243]

For each interval [x_k, x_(k+1)], you can solve the four equations

  1. p_k(x_k) = f(x_k) = y_k
  2. p_k'(x_k) = f'(x_k) = d_k
  3. p_k(x_(k+1)) = f(x_(k+1)) = y_(k+1)
  4. p_k'(x_(k+1)) = f'(x_(k+1)) = d_(k+1)

(without checking your code, I assume that this is what you did). From this, you can construct a dict

{'polynomials': [ [a_0, ..., d_0], ..., [a_24, ..., d_24] ],
 'knots': [x_0, ..., x_24]}

For each x of your 250 point, you check for which k the point x is in the interval [x_k, x_(k+1)] and evaluate p_k(x).

All of this is straight forward mathematics and python coding. If something is not clear, you are better of learning more about both fields, instead of getting specialized advise on this website.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM