在Python中创建函数depending of x,返回函数的组合depending of x

2024-04-18 22:24:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将函数f应用于数据X,即numpy数组。问题是f是函数的一种“线性组合”,比如说f_i,每个函数还依赖于另一个参数,比如说:

param = 1.0  #same param for every f_i call.
def f(x):
    for xi in range(len(x)):
       cummulate sum of f_i(x, xi, param)
    return the result of the loop, which depends of (x)

有什么帮助吗?我试过sympy,但是f_i不是简单的数学函数,而是它们的组合。你知道吗


Tags: ofthe数据函数innumpyfor参数
1条回答
网友
1楼 · 发布于 2024-04-18 22:24:21

你有一些方法。你知道吗

第一个也是最简单的方法是将params作为参数传入,它可以是每个函数的一个额外参数数组:

def f(x, params):
    for i in len(x):
        # Pass in params[i] to f_i

如果只需要f接受一个参数,可以使用closure执行第二种方法:

def f_creator(params):
    def closure(x):
        for i in len(x):
            # Pass in params[i] to f_i
    return closure

f = f_creator(... params for f_is go in here...)
# Use f for any special calculations that you need

最后,如果这些参数是常量,并且在程序运行过程中没有变化,则可以将它们设置为全局常量。不建议使用这种方法,因为它使测试变得困难,并且使代码对更改的鲁棒性降低。你知道吗

params = ....

def f(x):
    for i in len(x):
        # Calculate f_i using global params

相关问题 更多 >