#-*— coding:utf-8 -*-
#Program 0.3 Lagrange Interpolation
import matplotlib.pyplot as plt
import numpy as np
import scipy as np
import random #随机生成10个介于(-255,255)的结点
def getdata():
a = np.zeros(10, np.double)
b = np.zeros(10, np.double) for i in range(len(a)):
a[i] = np.random.uniform(-255, 255) #随机生成介于-255到255的数
b[i] = np.random.uniform(-255, 255) return a, b #x, y 为已知插值结点
x, y = getdata() #xn为新的x值
def Lagrange(x, y, xn):
ans = 0.0 #两重循环实现插值
for i in range(len(y)):
t = y[i]
for j in range(len(y)):
if i != j:
t *= (xn - x[j]) / (x[i] - x[j])
ans += t
return ans #开始插值
xn = np.arange(-255, 255, 1)
yn = np.zeros(len(xn)) for i in range(len(xn)):
yn[i] = Lagrange(x, y, xn[i]) plt.plot(x, y, 'r*') #已知结点
plt.plot(xn, yn, '-') #插值结果
plt.title('Lagrange Interpolation')
plt.show()