【问题标题】:Convert a python list into function将python列表转换为函数
【发布时间】:2014-11-27 21:25:58
【问题描述】:

我正在做一些数值分析,因此我有一系列形式为

的 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)

【问题讨论】:

    标签: python function piecewise


    【解决方案1】:

    scipy's 1d interpolation 函数会起作用吗?

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-23
      • 1970-01-01
      • 2016-02-05
      • 2021-04-12
      • 2021-03-22
      • 2012-06-13
      • 2011-09-23
      相关资源
      最近更新 更多