3

Consider the follwing example:

from sympy import *
x = Symbol('x')
f = sqrt(3*x + 2)

Now I want to substitute a number, say 5 for x and get a LaTeX represenation, in this case it should return

\\sqrt(3\\cdot 5 + 2)

How can I do this?

I tried latex(f.subs(x,2,evaluate=False)) but this results just in \\sqrt(17).

1 Answer 1

3

Use UnevaluatedExpr(5) instead of 5:

>>> latex(f.subs(x, UnevaluatedExpr(5)))
'\\sqrt{2 + 3 \\cdot 5}'

This wrapper prevents the expression inside of it ("5") from interacting with the outside terms. Reference: Prevent expression evaluation


The order of addends isn't the same after substitution, as 3*x + 2 and 3*5 + 2 get sorted differently by the printer. To avoid this, one can use order='none' which keeps whatever internal order the arguments have, without trying to put them in a human-friendly arrangement.

>>> latex(f, order='none')
'\\sqrt{2 + 3 x}'
>>> latex(f.subs(x, UnevaluatedExpr(5)), order='none')
'\\sqrt{2 + 3 \\cdot 5}'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.