先是逐步插值,主体十分简单,关键在于算法部分,我运用了矩阵的数据结构来存储每次迭代后的新值。角标的循环初看可能有些复杂,自己动手走一遍就会很清楚啦
1 #coding=gbk 2 ‘‘‘ 3 Created on 2014-8-31 4 5 @author: Administrator 6 ‘‘‘ 7 8 def Neville(xt,m,n,x): 9 for i in range(1,n): 10 for j in range(1,n): 11 w[i-j][i]=(x-xt[i-j])/(xt[i]-xt[i-j]) 12 m[i][j]=m[i-1][j-1]+w[i-j][i]*(m[i][j-1]-m[i-1][j-1]) 13 for i in range(n): 14 for j in range(0,i+1): 15 if j%n==0: 16 print("\n") 17 print(‘ %f‘ %m[i][j]) 18 19 n = int(input(‘插入节点个数:‘)) 20 x = float(input(‘输入x的值:‘)) 21 m = [[0 for i in range(n)] for j in range(n)] #创建n*n矩阵 22 w = [[0 for i in range(n)] for j in range(n)] 23 xt = [0]*n 24 for i in range(n): 25 m[i][0] = float(input(‘插入第%d个y值:‘ %(i+1))) 26 for i in range(n): 27 xt[i] = float(input(‘插入第%d个x值:‘ %(i+1))) 28 Neville(xt,m,n,x)
下面的是拉格朗日插值算法,十分简单,分享借鉴。
1 #coding=gbk 2 ‘‘‘ 3 Created on 2014-8-31 4 5 @author: Administrator 6 ‘‘‘ 7 def lagrange(x,xt,yt): 8 y = 0 9 for i in range(3): 10 t = 1 11 for j in range(3): 12 if i!=j: 13 t = t*(x-xt[j])/(xt[i]-xt[j]) 14 y = y+t*yt[i] 15 print("结果为:%f" %y) 16 17 xt = [] 18 yt = [] 19 x = float(input("插值x;")) 20 n = int(input("节点数目;")) 21 for i in range(n): 22 xt.append(float(input("第%d个x的值" %(i+1)))) 23 for i in range(n): 24 yt.append(float(input("第%d个x的值" %(i+1)))) 25 26 lagrange(x,xt,yt)
时间: 2024-10-10 05:43:49