不能用衍生物表达同情表达

loading...


1

我不能lambdify包含衍生物的表达式 . 以下是解释问题的最小代码:

import sympy
x = sympy.symbols('x', real=True)
a = sympy.Function('a')(x)
b = a**2
r = sympy.diff(b, x)
sympy.lambdify((a), b)  # works
r.evalf(subs={diff(a, x): 1, a: 2})  # works 
b_x = sympy.lambdify((diff(a, x), a), r)  # throws an error

最后一行代码抛出以下错误:

Traceback (most recent call last):   File "C:\Anaconda2\lib\site-packages\IPython\core\interactiveshell.py", line 2882, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)   File "<ipython-input-29-a0069a059795>", line 2, in <module>
    gx = sympy.lambdify((diff(a, x), a), r)  # gives an error   File "C:\Anaconda2\lib\site-packages\sympy\utilities\lambdify.py", line 434, in lambdify
    func = eval(lstr, namespace)   File "<string>", line 1
    lambda Derivative(a(x), x),_Dummy_29: (2*Derivative(_Dummy_29, x)*_Dummy_29)
                     ^ SyntaxError: invalid syntax
1回答

  • 4

    lambdify 尝试用等效数字替换符号函数,并返回一个可以接受数值或数组并返回数字或数组的函数 .

    错误消息

    lambda Derivative(a(x), x),_Dummy_29: (2*Derivative(_Dummy_29, x)*_Dummy_29)
                         ^ SyntaxError: invalid syntax
    

    表明lambdify正在尝试构建一个lambda函数,其第一个参数是 Derivative(a(x), x) . 显然这不会起作用 . 我们需要一个裸变量名而不是符号表达式 Derivative(a(x), x) .

    所以用一个裸符号 da 替换 Derivative(a(x), x)

    import sympy
    x = sympy.symbols('x', real=True)
    a = sympy.Function('a')(x)
    b = a**2
    r = sympy.diff(b, x)
    da = sympy.symbols('da')
    b_x = sympy.lambdify((da, a), r.subs([(sympy.diff(a, x), da)]))
    assert b_x(1, 2) == r.evalf(subs={sympy.diff(a, x): 1, a: 2})
    # 4
    

loading...

评论

暂时没有评论!