python - 从函数返回表达式之和的 Python 方式是什么?

标签 python arrays python-3.x function numpy

我有一个函数F,定义为:

def F(x, A_0, A_1, phi_1, freq):
    return (A_0 + A_1 * np.sin(2 * np.pi * 1 * freq * x + phi_1))

有时我希望将其扩展为这种形式:

def F(x, A_0, A_1, phi_1, A_2, phi_2, freq):
    return (A_0 + A_1 * np.sin(2 * np.pi * 1 * freq * x + phi_1)
                + A_2 * np.sin(2 * np.pi * 2 * freq * x + phi_2))

我希望能够将该函数扩展到任意多个sin项。从数学上讲,我希望函数返回:

enter image description here

执行此操作的 Python 方法是什么?

我的做法:

def F(x, A_0, As, phis, freq):
    terms=[]
    for i, A_i in enumerate(As):
        terms.append(A_i*np.sin(2*np.pi*i*freq * x +phis[i]))
    return A_0 +  sum(terms)

如何做得更好?

最佳答案

您可以使用生成器表达式并避免创建中间列表:

def F(x, A_0, As, phis, freq):
    terms = (A_i*np.sin(2*np.pi*i*freq * x +phis[i]) for i, A_i in enumerate(As))
    return A_0 +  sum(terms)

使用 NumPy 更好的想法是矢量化你的逻辑:

def F(x, A_0, As, phis, freq):
    idx = np.arange(len(As))
    terms = As * np.sin(2 * np.pi * idx * freq * x + phis)
    return A_0 + terms.sum()

要了解其工作原理,请注意应用于数组的 np.sin 返回的数组的形状与将 np.sin 应用于每个 值。

正如 @Oleg 的评论中所述,您可能需要 np.arange(1, len(A_i)+1) 来确保您的枚举从 1 开始。

关于python - 从函数返回表达式之和的 Python 方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54514886/

相关文章:

python - 在Python上绘制带有 turtle 图形的条形码

python - 如何在 QTableWidget 中自定义排序行为

arrays - 生成伪语言的 C 程序 - 全局 3D 数组太大(段错误)?

python - 根据最大数量 pandas Dataframe 将订单数据分割成新行

java - double 组——最常见的值方法? (没有 HashMap 或排序)

ruby - 数组类型错误 : can't convert Fixnum into String

python-3.x - 语法错误 : invalid syntax while running Job

python - 当我关闭 sublimerepl 选项卡时,如何让 sublimerepl 关闭它创建的 Python 实例?

python - "Can only join an iterable" python 错误

python - setup.py 缺少 __init__.py 文件