gpt4 book ai didi

python - 我想在给定的虚拟函数中更新我的函数 interpolate()

转载 作者:行者123 更新时间:2023-11-28 18:36:22 26 4
gpt4 key购买 nike

我是编程新手,我会尝试编写一个线性插值函数:

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

我如何制作一个元组(即数据 = ( (2, 1), (3, 1.5), (6, 3) ))并以干净的方式迭代该元组。

最佳答案

"""让我的功能"""

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

"""感谢帮助和支持"""

关于python - 我想在给定的虚拟函数中更新我的函数 interpolate(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32085961/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com