erwanp/pytexit

Python expression (in string format) not correctly converted to LaTeX

shashikulk opened this issue · 2 comments

I am trying to convert Python expressions to LaTeX using py2tex(). See the code and the output as given below.

from pytexit import py2tex

string_list = ["a=(x+y)-(x-y)", "b=-(3x-2y)", "c=-(-4x+5y)", "d=(x+y)+(a-b)-(p-q)"]
for txt_str in string_list:
    print('expression is ', txt_str)
    try:
        temp = py2tex(txt_str, tex_enclosure=' ')
        print('latex conversion is ', temp)
    except Exception as e:
        print("some error in py2tex: [", e, "] and expression is: [[", txt_str, ']]')

The output is as follows -

expression is  a=(x+y)-(x-y)
<IPython.core.display.Latex object>
 a=x+y-x-y 
latex conversion is   a=x+y-x-y 
expression is  b=-(3x-2y)
some error in py2tex: [ invalid decimal literal (<unknown>, line 1) ] and expression is: [[ b=-(3x-2y) ]]
expression is  c=-(-4x+5y)
some error in py2tex: [ invalid decimal literal (<unknown>, line 1) ] and expression is: [[ c=-(-4x+5y) ]]
expression is  d=(x+y)+(a-b)-(p-q)
<IPython.core.display.Latex object>
 d=x+y+a-b-p-q 
latex conversion is   d=x+y+a-b-p-q 

As we can see, the LaTeX output for expressions a=(x+y)-(x-y) and d=(x+y)+(a-b)-(p-q) is incorrect, because the parentheses have been removed without changing signs thereby making them mathematically different from the original expressions.
In case of expressions b=-(3x-2y) and c=-(-4x+5y), py2tex is getting an error and not able to convert to LaTeX.

I am not sure if I am missing anything while passing parameters to py2tex(). Would like to get help in resolving these issues. Any help will be greatly appreciated.

Regards,
Shashikant

Thank you for reporting!
This issue has now been solved with commit eb5d2d6. Appropriate tests have been added as well in order to ensure future consistency.

For your expressions a=(x+y)-(x-y) and d=(x+y)+(a-b)-(p-q) the parentheses are kept for the subtracted terms, while parentheses for the positive terms are removed as unnecessary.

The other two expressions work as well correctly now when providing correct Python expressions: b=-(3*x-2*y) and c=-(-4*x+5*y) (added missing multiplication signs).

Thanks for your response and for providing a solution!