(-6x ^ 2-x-7)(2x ^ 3 + 3x ^ 2-2x-5)作为SymPy中的输入

时间:2014-10-08 05:48:08

标签: python scipy latex sympy tex

SymPy中是否有任何函数可以将此表达式作为输入

(-6x^2-x-7)(2x^3+3x^2-2x-5)

找到衍生物?

1 个答案:

答案 0 :(得分:1)

parsing 模块中有多种解析器。

可能有更好的方法,但这有效:

from sympy import *
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations,               \
                                       implicit_multiplication_application

transformations = (standard_transformations + ( implicit_multiplication_application, ) )

>>> var('x')
x

>>> s = '(-6x^2-x-7)(2x^3+3x^2-2x-5)'
>>> parse_expr( s.replace( "^", "**" ), transformations = transformations )
(-6*x**2 - x - 7)*(2*x**3 + 3*x**2 - 2*x - 5)

>>> _.diff(x)
(-12*x - 1)*(2*x**3 + 3*x**2 - 2*x - 5) + (-6*x**2 - x - 7)*(6*x**2 + 6*x - 2)

但我发现 mathematica 解析器中的规则只需要进行调整,然后您可以执行以下操作:

from sympy.parsing.mathematica import mathematica as M
from sympy.abc import x

M( '(-6x^2-x-7)(2x^3+3x^2-2x-5)' ).diff(x)

mathematica 解析器会出错

from sympy.parsing.mathematica import mathematica as M
from sympy.abc import x

M( '(-6x^2-x-7)(2x^3+3x^2-2x-5)' ).diff(x)
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\sympy\core\sympify.py", line 313, in sympify
expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate)
File "C:\Python34\lib\site-packages\sympy\parsing\sympy_parser.py", line 757, in parse_expr
return eval_expr(code, local_dict, global_dict)
File "C:\Python34\lib\site-packages\sympy\parsing\sympy_parser.py", line 691, in eval_expr
code, global_dict, local_dict)  # take local objects in preference
File "<string>", line 1
(-Integer (6 )Symbol ('x' )**Integer (2 )-Symbol ('x' )-Integer (7 ))*(Integer (2 )*Symbol ('x' )**Integer (3 )+Integer (3 )*Symbol ('x' )**Integer (2 )-Integer (2 )*Symbol ('x' )-Integer (5 ))
                               ^
SyntaxError: invalid syntax

在处理上述异常期间,发生了另一个异常:

Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
M('(-6x^2-x-7)(2x^3+3x^2-2x-5)').diff(x)
File "C:\Python34\lib\site-packages\sympy\parsing\mathematica.py", line 8, in mathematica
return sympify(parse(s))
File "C:\Python34\lib\site-packages\sympy\core\sympify.py", line 315, in sympify
raise SympifyError('could not parse %r' % a, exc)
sympy.core.sympify.SympifyError: Sympify of expression 'could not parse '(-6x**2-x-7)*(2*x**3+3*x**2-2*x-5)'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)