2014-10-08 35 views

回答

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) 
+0

Mathematica的解析器似乎不錯,但在這裏它只是給出了錯誤,你試過嗎? – iMath 2014-10-09 02:11:56

+0

'parse_expr'絕對是你最好的選擇。 – asmeurer 2014-10-13 01:24:31

+0

當前主數學中的mathematica現在工作 – smichr 2014-10-13 16:29:42