Search code examples
pythonsympymathjaxmathml

About parentheses bug in sympy.printing.mathml


I converted a Python string into a formula with sympify as follows:

I converted the formula into MathML format with the mathml command.

from sympy import *
from sympy.printing.mathml import mathml

print(mathml(sympify("(2*x + 3*y + 1)*(4*x**2 - 6*x*y - 2*x + 9*y**2 - 3*y + 1)"),printer='presentation'))

As a result, the following code was output.

<mrow><mrow><mrow><mn>2</mn><mo>&InvisibleTimes;</mo><mi>x</mi></mrow><mo>+</mo><mrow><mn>3</mn><mo>&InvisibleTimes;</mo><mi>y</mi></mrow><mo>+</mo><mn>1</mn></mrow><mo>&InvisibleTimes;</mo><mrow><mrow><mn>4</mn><mo>&InvisibleTimes;</mo><msup><mi>x</mi><mn>2</mn></msup></mrow><mo>-</mo><mrow><mn>6</mn><mo>&InvisibleTimes;</mo><mi>x</mi><mo>&InvisibleTimes;</mo><mi>y</mi></mrow><mo>-</mo><mrow><mn>2</mn><mo>&InvisibleTimes;</mo><mi>x</mi></mrow><mo>+</mo><mrow><mn>9</mn><mo>&InvisibleTimes;</mo><msup><mi>y</mi><mn>2</mn></msup></mrow><mo>-</mo><mrow><mn>3</mn><mo>&InvisibleTimes;</mo><mi>y</mi></mrow><mo>+</mo><mn>1</mn></mrow></mrow>

I embedded the code in HTML and tried it as follows.

test.html

<html>
<head>
  <script async="" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_CHTML"></script>
</head>
<body>
<math>
<mrow><mrow><mrow><mn>2</mn><mo>&InvisibleTimes;</mo><mi>x</mi></mrow><mo>+</mo><mrow><mn>3</mn><mo>&InvisibleTimes;</mo><mi>y</mi></mrow><mo>+</mo><mn>1</mn></mrow><mo>&InvisibleTimes;</mo><mrow><mrow><mn>4</mn><mo>&InvisibleTimes;</mo><msup><mi>x</mi><mn>2</mn></msup></mrow><mo>-</mo><mrow><mn>6</mn><mo>&InvisibleTimes;</mo><mi>x</mi><mo>&InvisibleTimes;</mo><mi>y</mi></mrow><mo>-</mo><mrow><mn>2</mn><mo>&InvisibleTimes;</mo><mi>x</mi></mrow><mo>+</mo><mrow><mn>9</mn><mo>&InvisibleTimes;</mo><msup><mi>y</mi><mn>2</mn></msup></mrow><mo>-</mo><mrow><mn>3</mn><mo>&InvisibleTimes;</mo><mi>y</mi></mrow><mo>+</mo><mn>1</mn></mrow></mrow>
</math>
</body>
</html>

However, with this code, the output will be missing the Parentheses, as in the image below.

[![画像の説明をここに入力][1]][1]

I read the [source code of sympy.printing.mathml][2].

So I wondered what the _print_Interval method is used for.

Is this related to the problem of missing Parentheses in formulas?

This expression is an example. I want to convert even more complicated formulas properly.


Solution

  • I got the answer in the Japanese version of stackoverflow. https://ja.stackoverflow.com/q/55578/22541

    Fixing [this][1] can solve the problem.

    [Before]

    for term in terms:
        x = self._print(term)
        mrow.appendChild(x)
    

    [After]

    for term in terms:
        mrow.appendChild(self.parenthesize(term, PRECEDENCE['Mul']))