Lagrange Interpolation

拉格朗日插值算法

源代码:

'''
Lagrange Interpolation
Implement Lagrange interpolation using Python
Author:Tu ZhiMing
'''

import numpy as np
import matplotlib.pyplot as plt

class Lagrange:
    '''
    Lagrange Interpolation Class
    '''
    def __init__(self, x ,y):

        self.x = x
        self.y = y

        self.nx = len(x)
        self.yk = y
        self.lk_den = np.ones(self.nx)

        for i in range(self.nx):
            for j in range(self.nx):
                if i==j:
                    continue
                self.lk_den[i]*=self.x[i]-self.x[j]

    def calc(self , x):
        if x < self.x[0]:
            return None
        elif x > self.x[-1]:
            return None

        lk_num = np.ones(self.nx)
        y = 0.0
        for i in range(self.nx):
            for j in range(self.nx):
                if i==j:
                    continue
                lk_num[i] *= x -self.x[j]
            y += self.yk[i] * lk_num[i]/self.lk_den[i]
        return y

def main():
    # example #1: x**2
    xp = [1.0, 2.0, 3.0]
    yp = [1.0, 4.0, 9.0]
    x = 1.5
    Lagrange1 = Lagrange(xp,yp)
    print("\nExample #1: ")
    zipped_x_y = list(zip(xp, yp))
    print("Given points: ", zipped_x_y)
    print("interpolated y value = %.3f at x = %.3f"% (Lagrange1.calc(x),x))

    #example #2: x**3
    xp = [1.0, 2.0, 3.0]
    yp = [1.0, 8.0, 27.0]
    x = 2.5
    Lagrange2 = Lagrange(xp, yp)
    print("\nExample #2: ")
    zipped_x_y = list(zip(xp, yp))
    print("Given points: ", zipped_x_y)
    print("interpolated y value = %.3f at x = %.3f" % (Lagrange2.calc(x),x))

if __name__ == '__main__':
    main()

运行结果:

Example #1: 
Given points:  [(1.0, 1.0), (2.0, 4.0), (3.0, 9.0)]
interpolated y value = 2.250 at x = 1.500

Example #2: 
Given points:  [(1.0, 1.0), (2.0, 8.0), (3.0, 27.0)]
interpolated y value = 16.000 at x = 2.500

Process finished with exit code 0

  目录