马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import numpy as np
class Interpolation:
def Lagrange(self, xx, x, y):
m = len(x)
n = len(y)
if m != n:
print("x与y维数不同")
s = np.ones(len(x))
for i in range(0, n):
d = 1
for j in range(0, n):
if i != j:
d = d * (xx - x[j]) / (x[i] - x[j])
s[i] = d
f = y * s
return sum(f)
class Main:
def run(self):
input_str = input("请输入一个x列表(用空格分隔各元素): ")
x = [int(i) for i in input_str.split()]
input_str = input("请输入一个y列表(用空格分隔各元素): ")
y = [int(i) for i in input_str.split()]
print("输入的列表为:\n", x, '\n', y)
interpolator = Interpolation()
while True:
a = input("是否输入插值点(Y/N)\n")
if a.lower() == 'n':
break
xx = int(input("请输入插值点: "))
print(interpolator.Lagrange(xx, x, y))
#如果以文件形式,文件内以元组((x1,y1),(x2,y2)...)形式传入
'''
class Main:
def read_data_from_file(self, file_path):
data = []
with open(file_path, 'r') as file:
lines = file.readlines()
for line in lines:
line = line.strip()
if line:
pair = tuple(map(int, line.split(',')))
data.append(pair)
return data
def run(self):
file_path = input("请输入包含数据的文件路径:")
data = self.read_data_from_file(file_path)
x = []
y = []
for pair in data:
x.append(pair[0])
y.append(pair[1])
print("输入的列表为:\n", x, '\n', y)
interpolator = Interpolation()
while True:
a = input("是否输入插值点(Y/N)\n")
if a.lower() == 'n':
break
xx = int(input("请输入插值点: "))
print(interpolator.Lagrange(xx, x, y))
'''
if __name__ == "__main__":
main = Main()
main.run()
|