1 #coding=utf-8 2 from numpy import * 3 import numpy as np 4 from sympy import * 5 x = Symbol("x") 6 7 # xi = [1,3,2]#存储x的值 8 # yi = [1,2,-1]#存储y 的值 9 def getL(xi,yi,n): 10 # i 循环用于求 L(x) 11 L = 0.0 12 for i in range(0,n): 13 # j 循环用于求 li(x) 14 li = 1.0 15 a = 1.0 # a表示分子 16 b = 1.0# b表示分母 17 for j in range(0,n): 18 if i ==j: # 保证一项为1 跳出循环 19 continue 20 21 a = a*(x-xi[j]) 22 b = b*(xi[j]-xi[i]) 23 24 li = a/b*yi[i] 25 L = L+ li 26 return L 27 28 # 输入相关数值 29 n=input("请输入取到样点数目:") 30 xi = [] 31 yi = [] 32 for k in range(0,n): 33 inputX = "请输入第"+str(k+1)+"个点 X:" 34 inputY = "请输入第"+str(k+1)+"个点 Y:" 35 xi.append(input(inputX)) 36 yi.append(input(inputY)) 37 # 取得多项式 38 L = getL(xi,yi,3) 39 # 输入x求估值 40 L=L.subs(x,float(input("输入x: "))) 41 print L