Lagrange插值法
阿新 • • 發佈:2018-11-19
一、簡介
對實踐中的某個物理量進行觀測,在若干個不同的地方得到相應的觀測值,拉格朗日插值法可以找到一個多項式,其恰好在各個觀測的點取到觀測到的值。這樣的多項式稱為拉格朗日(插值)多項式。
二、實現
# -*- 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')