簡體   English   中英

當執行Sympify時,將切換表達式的順序(Python的Sympy)

[英]When Sympify is executed, the order of expressions is switched (Python's Sympy)

我運行了以下程序

from sympy import *

str = "Abs(a)*(β-α)**3/6"
print(str)
print(sympify(str))

執行結果如下。

Abs(a)*(β-α)**3/6
(-α + β)**3*Abs(a)/6

由於執行sympify ,表達式的順序已更改。

我要匹配執行結果,如下所示。

Abs(a)*(β-α)**3/6
Abs(a)*(β-α)**3/6

我該怎么辦?


我要這樣做的原因是,我不想在將表達式轉換為mathml格式時使它看起來很奇怪。

str = "Abs(a)*(β-α)**3/6"
print(mathml(sympify(str),printer='presentation'))

執行上述程序時,將輸出以下內容。

<mrow><mfrac><mrow><msup><mfenced><mrow><mrow><mo>-</mo><mi>&#945;</mi></mrow><mo>+</mo><mi>&#946;</mi></mrow></mfenced><mn>3</mn></msup><mo>&InvisibleTimes;</mo><mrow><mfenced clos
e="|" open="|"><mi>a</mi></mfenced></mrow></mrow><mn>6</mn></mfrac></mrow>

如下圖所示。

在此處輸入圖片說明

我希望公式看起來像下面的圖像。

在此處輸入圖片說明

如果您將以下差異應用於SymPy,我認為您的案例會起作用:

diff --git a/sympy/printing/str.py b/sympy/printing/str.py
index ee560ca..cb0db5e 100644
--- a/sympy/printing/str.py
+++ b/sympy/printing/str.py
@@ -51,6 +51,8 @@ def _print_Add(self, expr, order=None):

         PREC = precedence(expr)
         l = []
+        if len(terms) == 2 and str(terms[0])[0] == '-' and str(terms[1])[0] != '-':
+            terms.reverse()
         for term in terms:
             t = self._print(term)
             if t.startswith('-'):

(它打印出的b - a相同,而不是-a + b 。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM