0

我正在做一些数值分析,其中我有一系列形式的 python 列表

listn = [1, 3.1, 4.2]

我想将这些转换为映射到 x_0 和 x_1 之间域的函数,因此我可以将函数对象传递给我用来分析数据的高阶函数。(在指定域之外,函数被选择为零)。为了我的目的,产生的函数需要是连续的,目前我只是返回一个分段线性函数。

我想出了下面复杂的解决方案,但是必须有更好的方法在几行中做到这一点?

def to_function(array_like, x_0=0, x_1=1):
    assert x_1 > x_0, "X_0 > X_1"
    def g(s, a=array_like, lower=x_0, upper=x_1):

        if lower < s <= upper:
            scaled = (1.0*(s-lower) / (upper - lower)) * (len(a) - 1)
            dec, whole = math.modf(scaled)
            return (1.0 - dec) * a[int(whole)] + dec * a[int(whole + 1)]
        else:
            return 0

    return g

 b = to_function([0, 1, 2, 3, 4, 5], x_0=0, x_1=5)
 print b(1)
 print b(2)
 print b(3)
 print b(3.4)
4

1 回答 1

1

scipy的一维插值函数会起作用吗?

import numpy as np
from scipy.interpolate import interp1d

x = y = np.arange(5)
f = interp1d(x,y, kind="linear", fill_value=0., bounds_error=False)

print f(0)
print f(2)
print f(3)
print f(3.4)

这使:

1.0
2.0
3.0
3.4
于 2014-11-27T21:47:16.173 回答