Cubic Spline Interpolation

The following Python code is implemented from a pseudo code in Burden & Faires, “Numerical Analysis” 8th edition

# author : worasait suwannik
# date   : apr 2015

def cubic_spline(n, x, y):
  h = [x[i+1]-x[i] for i in range(n)]
  al = [3*(y[i+1]-y[i])/h[i] - 3*(y[i]-y[i-1])/h[i-1] for i in range(1,n)]
  al.insert(0,0)
  
  l = [1] * (n+1)
  u = [0] * (n+1)
  z = [0] * (n+1)
  for i in range(1, n):
    l[i] = 2*(x[i+1]-x[i-1]) - h[i-1]*u[i-1]
    u[i] = h[i]/l[i]
    z[i] = (al[i] - h[i-1]*z[i-1])/l[i]
  
  b = [0] * (n+1)
  c = [0] * (n+1)
  d = [0] * (n+1)
  for i in reversed(range(n)):
    c[i] = z[i] - u[i]*c[i+1]
    b[i] = (y[i+1]-y[i])/h[i] - h[i]*(c[i+1] + 2*c[i])/3
    d[i] = (c[i+1]-c[i])/(3*h[i])
  return [y, b, c, d]
  
if __name__ == '__main__':
  import math
  a = cubic_spline(3, [i for i in range(4)], [math.e ** i for i in range(4)])
  print(a)

ทดลองรันและดูกราฟได้ที่ https://trinket.io/python/0793687aa3 เส้นสีดำคือ e^x ส่วนเส้นสีแดง เขียว น้ำเงิน เป็นการประมาณค่าในช่วง [0,1], [1,2], [2,3] ตามลำดับ

สอนเขียน Python

Numerical Method using Python

หากจะนำข้อความไปใช้ ต้องแสดงที่มา และห้ามใช้ในเชิงพาณิชย์

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s