Sympy Multiplication Prevention

I am generating an expression with two fractions and want to pretty print as a whole expression with LaTeX and then overlay the worksheet.

eg. in the shape of:

(5/7) * (3/4). 

However, when I do the following:

fract1 = sympy.sympify(Fraction(5,7))
fract2 = sympy.sympify(Fraction(3,4))
expression = sympy.Mul(fract1,fract2,evaluate=False)

He returns

5*3/(7*4)

Obviously, it combines the fraction, but does not actually evaluate, but I want to be able to create it in a format suitable for the question for the math sheet.

+4
source share
2 answers

The next version of SymPy will UnevaluatedExpr:

In [4]: uexpr = UnevaluatedExpr(S.One*5/7)*UnevaluatedExpr(S.One*3/4)

In [7]: uexpr
Out[7]: 5/7⋅3/4

To release and evaluate it, simply use .doit():

In [8]: uexpr.doit()
Out[8]: 
15
──
28

LaTeX output looks like this:

In [10]: print(latex(uexpr))
\frac{5}{7} \frac{3}{4}

​​, .

+2

( ):

def print_fractions(expr):
    print("({}) * ({})".format(*expr.args))

:

In:  expr = sympy.Mul(sympy.S("5/7"), sympy.S("3/4"), evaluate=False)
In:  expr
Out: 5*3/(7*4)
In:  print_fractions(expr)
Out: (5/7) * (3/4)

srepr, expr, , sympy :

In:  sympy.srepr(expr)
Out: 'Mul(Rational(5, 7), Rational(3, 4))'

sympy.Mul __str__:

class MyMul(sympy.Mul):
    def __str__(self):
        return "({}) * ({})".format(*self.args)

:

In:  expr = MyMul(sympy.S("5/7"), sympy.S("3/4"), evaluate=False)
In:  print(expr)
Out: (5/7) * (3/4)

Eidt: latex()

, :

class MyMul(Mul):
    def _latex(self, _):
        return r"\left({} \cdot {}\right)".format(*map(latex, self.args))

:

In:  a = S("5/7")
In:  b = S("3/4")
In:  c = MyMul(a, b, evaluate=False)
In:  print(latex(c))
Out: \left(\frac{5}{7} \cdot \frac{3}{4}\right)

, , _latex .

+2

Source: https://habr.com/ru/post/1670930/


All Articles