python - 获取 Python 函数并生成所有导数

标签 python lambda python-2.7 scipy sympy

我有一个参数数量可变的 python 函数:

F(x1, x2, ... , xN)

我想自动生成 N 个函数,表示 F 对每个参数的导数。

F'_1 = dF/dx1
F'_2 = dF/dx2
...
F'_N = dF/dxN

例如,我可以同时提供 F(x1) = sin(x1) 和 F(x1, x2) = sin(x1) * cos(x2) 并自动获取所有的衍生品。


编辑2: 如果函数 F 是 2 个变量(固定数量的参数),我可以使用

   def f(x,y):
      return  sin(x)*cos(y)

   from sympy import *
   x, y = symbols('x y')
   f_1 = lambdify((x,y), f(x,y).diff(x))

最佳答案

诀窍是使用 inspect.getargspec 获取函数所有参数的名称。之后就是简单的列表推导:

import inspect
from sympy import *

def get_derivatives(func):
    arg_symbols = symbols(inspect.getargspec(func).args)
    sym_func = func(*arg_symbols)

    return [lambdify(arg_symbols, sym_func.diff(a)) for a in arg_symbols]

例如:

def f(x, y):
    return sin(x)*cos(y)

all_derivatives = get_derivatives(f)

关于python - 获取 Python 函数并生成所有导数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14178101/

相关文章:

python - 在方法中运行时,内置 type() 函数的行为有所不同

python - 属性错误 : xmlNode instance has no attribute 'isCountNode'

c# - 用 Linq 合并 List<T>?

c# - 优化通用列表 WHERE

function - 为什么要编写一个带有名称的 C++ lambda 以便可以从某个地方调用它?

python - 如何在 MS Windows 操作系统上使用 Google 的 repo 工具?

django - django queryset.values_list()中datetime字段到字符串的转换

python - EOF 发生在违反 Python ftplib 协议(protocol)的情况下

python - 当满足其余行中的条件时更新 Pandas Dataframe 行中的列(在 SQL UPDATE 中)

python - 从源代码 : multiple threads for tests? 编译 Python