python - 如何通过更改参数对的数量动态创建函数

标签 python function

所以我一直在尝试在运行时创建一个函数,它应该动态添加参数对。为了了解我在寻找什么,这是我到目前为止所做的:

def smart_func(terms):
    params = []
    for n in range(terms):
        params.append((2*n*np.pi, 2*n*np.pi))

    def func(t, freq, offset, *params):
        result = 0
        for (a,b) in zip(params):
            result += np.sin(a*freq*t) + np.cos(b*freq*t)
        return result
    return func

我知道这行不通,但应该让我知道我正在尝试做什么。我看过这个question但仍无法提出解决方案。

为了给出更多的解释,我需要将这个新创建的函数传递给它

from scipy.optimize import curve_fit
    f_vars, f_cov = curve_fit(smart_func(terms=3), time_in_hours, full_fit_flux, p0=p0)

这将使我能够轻松确定充分拟合我的数据所需的最少参数。

这是我成功使用过的硬编码函数。如果 smart_func 有一个 3 传递给它,它会返回这个函数。

    def func(t, freq, offset, a0, b0, a1, b1, a2, b2):
        return b0 + a0 \
            + a1*np.sin(2.*np.pi*freq*t) \
            + b1*np.cos(2.*np.pi*freq*t) \
            + a2*np.sin(4*np.pi*freq*t) \
            + b2*np.cos(4*np.pi*freq*t) \
            + offset

如果 smart_func 有一个 2 传递给它,这就是它的样子

    def func(t, freq, offset, a0, b0, a1, b1):
        return b0 + a0 \
            + a1*np.sin(2.*np.pi*freq*t) \
            + b1*np.cos(2.*np.pi*freq*t) \
            + offset

我想要的是根据指定的术语数量添加额外的 a 和 b 术语。

最佳答案

下面展示了如何动态创建所需的函数。请注意,我简化了动态函数的代码以最大程度地减少冗余计算。

from textwrap import dedent

def test(num_terms):

    def smart_func(num_terms):  # nested to mimic OP's usage
        template = dedent('''
            def func(t, freq, offset, a0, b0, {params}):
                ang = 2.*np.pi*freq*t
                sin_ang = np.sin(ang)
                cos_ang = np.cos(ang)
                return (a0 + b0
            {terms}
                        + offset)
            ''')
        indent = ' ' * 12
        params, terms = [], []
        for i in range(1, num_terms):
            params.append('a{i}, b{i}'.format(i=i))
            terms.append((indent + '+ a{i}*sin_ang\n' +
                          indent + '+ b{i}*cos_ang').format(i=i))

        src_code = template.format(params=', '.join(params), terms='    \n'.join(terms))

        print('Dynamically created function of {} terms:'.format(num_terms))
        print(src_code)

        exec(src_code, globals(), locals())  # compile into function object
#        exec src_code in globals(), locals()  # older Python 2 syntax

        return locals()['func']  # return compiled function

    return smart_func(num_terms)  # return result of calling nested function

print(test(3))

输出:

Dynamically created function of 3 terms:

def func(t, freq, offset, a0, b0, a1, b1, a2, b2):
    ang = 2.*np.pi*freq*t
    sin_ang = np.sin(ang)
    cos_ang = np.cos(ang)
    return (a0 + b0
            + a1*sin_ang
            + b1*cos_ang
            + a2*sin_ang
            + b2*cos_ang
            + offset)

<function func at 0x0232A228>

关于python - 如何通过更改参数对的数量动态创建函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45225506/

相关文章:

javascript - 有效检测图像尺寸

python - 如何打印出 Python 函数需要/允许哪些参数?

代码的调用流程 - C

用于标记匿名函数的 Javascript 'colon'?

c - 在 void 指针处存储结构对象

python - 将多个 StandardScaler 应用到各个组?

python - 如何理解这段python代码?

python - 在 python 中查找来自不同列表的匹配元素时遍历列表

Python range( ) 没有给我一个列表

python - 绘制超平面线性 SVM python