Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing a multiplication expression evaluating in Sympy

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

E.g. in the form:

(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)

It returns

5*3/(7*4)

Clearly it is combining the fraction but not actually evaluating, but I want to be able to produce it in a format suitable as a question for a maths worksheet.

like image 292
benjo456 Avatar asked Feb 27 '17 12:02

benjo456


1 Answers

The next SymPy version will have 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, just use .doit():

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

LaTeX output looks like:

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

This feature is available since SymPy 1.1. See the documentation to find out more.

like image 119
Francesco Bonazzi Avatar answered Sep 29 '22 08:09

Francesco Bonazzi