根据 x 在 Python 中创建函数,其中 returns 函数的组合取决于 x
Create function in Python depending of x which returns a composition of functions depending of x
我想将函数 f
应用于数据 X
,成为 X
numpy 数组。问题是 f
是一种 "linear combination" 函数,比方说 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
不是微不足道的数学函数,而是它们的组合。
这里有一些方法。
首先也是最简单的方法是将 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
我想将函数 f
应用于数据 X
,成为 X
numpy 数组。问题是 f
是一种 "linear combination" 函数,比方说 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
不是微不足道的数学函数,而是它们的组合。
这里有一些方法。
首先也是最简单的方法是将 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