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

标签 python python-2.7 python-3.x tuples interpolation

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

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/

相关文章:

python - mysql python 上的更新总是返回 0 作为lastrowid

python - 为 Python 包添加虚拟命名空间

python - 检索字典中最后一个键的值

python - 导出 .eps 文件时在 Matplotlib 中转换文本

python - 如何在 python 中引用变量?

python - 如何将字符串 json 转换为 python float 并返回 json 中的数字

python - 当输出保存在变量中时,为什么 .read() 命令会执行不同的操作

python - 按类型全选 : Geometry. 等效的 Python 脚本?

python - 我如何知道调用 create_all() 时 SQLAlchemy 是否必须创建表?

python - 如何在python中将数据库从cPanel连接到桌面