Lagrange插值法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tlzhatao/article/details/54425755

一、简介

对实践中的某个物理量进行观测,在若干个不同的地方得到相应的观测值,拉格朗日插值法可以找到一个多项式,其恰好在各个观测的点取到观测到的值。这样的多项式称为拉格朗日(插值)多项式。

详解

二、实现

# -*- coding: utf-8 -*-
"""
Created on Sun Dec 18 21:19:18 2016

    lagrange插值

@author: Administrator
"""

from numpy import *
import matplotlib.pyplot as plt

def f(x):
    return 1 / (1 + x**2)

def get_lagrange(xi,fi,n):
    def lagrange(x):
        y = 0
        for i in range(n):
            temp = 1
            for j in range(n):
                if i != j:
                    temp = temp * (x - xi[j]) / (xi[i] - xi[j])
            y = y + temp * fi[i]
        return y
    return lagrange

if __name__ == '__main__':
    n = 10
    x = linspace(-5,5,n)
    y = f(x)
    lx = get_lagrange(x,y,n)
    draw_x = linspace(-5,5,100)
    lx_y = lx(draw_x)
    f_y = f(draw_x)
    fig = plt.figure(figsize=(8,4))
    ax = fig.add_subplot(111)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.scatter(x, y, marker='o', color='r',label='interpolation point')
    ax.plot(draw_x,f_y,color='k',linestyle=':',label='f(x)')
    ax.plot(draw_x,lx_y,color='g',linestyle='--',label='lx(x)')
    ax.legend(loc='upper right')
    fig.show()
    fig.savefig('a.png')

Lagrange插值法

猜你喜欢

转载自blog.csdn.net/tlzhatao/article/details/54425755