我对编程很新,我会尝试编写线性插值函数:
from bisect import bisect_left
def interpolate((x_list, y_list), x_test):
if any(y - x <= 0 for x, y in zip(x_list, x_list[1:])):
raise ValueError("x_list must be in strictly ascending order!")
x_list = x_list = map(float, x_list)
y_list = y_list = map(float, y_list)
intervals = zip(x_list, x_list[1:], y_list, y_list[1:])
slopes = [(y2 - y1)/(x2 - x1) for x1, x2, y1, y2 in intervals]
i = bisect_left(x_list, x_test) - 1
return y_list[i] + slopes[i] * (x_test - x_list[i])
i=interpolate(((2, 3, 6), (1,1.5,3)),5)
print i
现在我想创建一个像这样的新函数(虚函数):
def interpolate(data, xtest):
#statements...
return numpy.interp(xtest, [x for (x,y) in data], [y for (x,y) in data])
给出如下数据:
data = ( (2, 1), (3, 1.5), (6, 3) )
interpolate(data, 4)
O/P : 2
interpolate(data, 5)
O/P : 2.5
我如何制作一个元组(即data =((2,1),(3,1.5),(6,3)))并以干净的方式迭代该元组。
答案 0 :(得分:1)
“”” 我的功能 “”“
def interpolate(data, x_text):
"""The interpolate function should return the value of f at the point x_test,as given by a linear interpolation from the sample points. """
data_dict={}
for item in data:
data_dict[item[0]] = item[1]
lst_x = data_dict.keys()
lst_x.sort()
"""Now find the co-ordinates of two points by using extrapolation and interpolation condition"""
# Condition 1(extrapolated):when x_text less than least value of lst_x.
if x_text <= lst_x[0]:
x_0 = lst_x[0]
x_1 = lst_x[1]
y_0 = data_dict[lst_x[0]]
y_1 = data_dict[lst_x[1]]
#Condition 2(extrapolated): When x_text is larger than largest value of lst_x.
elif x_text >= lst_x[-1]:
x_0 = lst_x[-2]
x_1 = lst_x[-1]
y_0 = data_dict[lst_x[-2]]
y_1 = data_dict[lst_x[-1]]
#Condition 3(interpolated): When x_text lies between two sample points, or exactly on one of the sample points.
else:
for i in range(len(data)-1):
if x_text >= lst_x[i] and x_text <= lst_x[i+1]:
x_0 = lst_x[i]
x_1 = lst_x[i+1]
y_0 = data_dict[lst_x[i]]
y_1 = data_dict[lst_x[i+1]]
break
# Calculation of interpolation point by using the equation.
y = y_1 + ((y_0-y_1)/float(x_0-x_1))*(x_text - x_1)
return y
“”“感谢帮助和支持”“”
答案 1 :(得分:0)
我认为你的问题是不言自明的。您似乎已经在第一个interpolate
函数中完成了迭代。我假设您想知道如何对元组进行基本迭代。
您的data
元组如下所示:
>>> data = ((2, 1), (3, 1.5), (6, 3))
要遍历此元组中的每个元组,请执行以下操作:
>>> for x in data:
... print x
...
(2, 1)
(3, 1.5)
(6, 3)
或者,在迭代时将元组的每个元素存储在变量x,y中:
>>> for x, y in data:
... print x, y
...
2 1
3 1.5
6 3
答案 2 :(得分:0)
我想你会问更多关于如何在列表元组和元组列表之间来回切换。内置函数zip
实现了两者。这是我在IPython中尝试使用NumPy的interp函数。
from numpy import sin, interp
x = range(10)
y = [ sin(i) for i in x ]
x
y
interp(2.5, x, y)
xy = zip(x,y)
xy
# xy is list of tuples: [ (x[0], y[0]), (x[1], y[1]), ... ]
u = zip(*xy)
u
# u is tuple of tuples: ( (x[0], x[1], ... ), (y[0], y[1], ... ) )
interp(2.5, u[0], u[1])
我不得不谷歌去讨论这个问题:Transpose/Unzip Function (inverse of zip)?,要知道zip(*...)
对解压缩元组列表这个聪明的伎俩。