Warm tip: This article is reproduced from stackoverflow.com, please click
math python python-3.x sympy symbolic-math

Unexpected behaviour when parsing string with sympy

发布于 2020-03-31 22:55:19

I'm trying to perform the derivative of an equation with sympy, but, while if I write the equation by hand the derivative is correct; when I pass the equation as a string, the output is wrong. Can anyone explain me how to solve this issue? I'm using python 3.6 and sympy 1.5.1.

>>>from sympy import *

>>>from operator import *

>>> x1 = symbols('x1')

>>> f = add(sin(x1), mul(x1, x1))

>>> diff(f, x1)

2*x1 + cos(x1)   ## Correct output

>>>> f = 'add(sin(x1), mul(x1, x1))'  ## Equation provided as string

>>>> diff(f, x1)

(Subs(Derivative(mul(_xi_1, x1), _xi_1), _xi_1, x1) + Subs(Derivative(mul(x1, _xi_2), _xi_2), _xi_2, x1))*Subs(Derivative(add(sin(x1), _xi_2), _xi_2), _xi_2, mul(x1, x1)) + cos(x1)*Subs(Derivative(add(_xi_1, mul(x1, x1)), _xi_1), _xi_1, sin(x1))  ## Wrong output
Questioner
Francesco
Viewed
67
CDJB 2020-01-31 20:09

This is happening because f = 'add(sin(x1), mul(x1, x1))' is not a valid mathematical equation that can be parsed by parse_expr. This function is designed to parse equations written in mathematical syntax, not in terms of Sympy functions. To get this function in particular to be parsed correctly, you would need to use, for example:

>>> f = 'sin(x1) +  x1^2'
>>> diff(f, x1)
2*x1 + cos(x1)

If you really need to use that specific string, you could use eval():

>>> f = 'add(sin(x1), mul(x1, x1))'
>>> diff(eval(f), x1)
2*x1 + cos(x1)